package com.icing.dialer.services

import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.telecom.TelecomManager
import android.util.Log
import androidx.core.content.ContextCompat
import android.content.pm.PackageManager
import android.Manifest

object CallService {
    private val TAG = "CallService"

    fun makeGsmCall(context: Context, phoneNumber: String, simSlot: Int = 0): Boolean {
        return try {
            val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
            val uri = Uri.parse("tel:$phoneNumber")

            if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                // Get available phone accounts (SIM cards)
                val phoneAccounts = telecomManager.callCapablePhoneAccounts
                
                if (phoneAccounts.isNotEmpty()) {
                    // Select the appropriate SIM slot
                    val selectedAccount = if (simSlot < phoneAccounts.size) {
                        phoneAccounts[simSlot]
                    } else {
                        // Fallback to first available SIM if requested slot doesn't exist
                        phoneAccounts[0]
                    }
                    
                    val extras = Bundle().apply {
                        putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, selectedAccount)
                    }
                    
                    telecomManager.placeCall(uri, extras)
                    Log.d(TAG, "Initiated call to $phoneNumber using SIM slot $simSlot")
                } else {
                    // No SIM cards available, make call without specifying SIM
                    telecomManager.placeCall(uri, Bundle())
                    Log.d(TAG, "Initiated call to $phoneNumber without SIM selection (no SIMs available)")
                }
                true
            } else {
                Log.e(TAG, "CALL_PHONE permission not granted")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error making GSM call: ${e.message}", e)
            false
        }
    }

    fun hangUpCall(context: Context): Boolean {
        return try {
            if (MyInCallService.currentCall != null) {
                MyInCallService.currentCall?.disconnect()
                Log.d(TAG, "Disconnected active call via MyInCallService")
                true
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
                telecomManager.endCall()
                Log.d(TAG, "Ended call via TelecomManager (no active call in MyInCallService)")
                true
            } else {
                Log.e(TAG, "No active call and hangup not supported below Android P")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error hanging up call: ${e.message}", e)
            false
        }
    }
}