package com.humand.demo.modules.CallService

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import io.getstream.android.video.generated.models.OwnCapability
import io.getstream.video.android.core.Call
import io.getstream.video.android.core.permission.android.StreamPermissionCheck

/**
 * Custom permission check that always requires microphone access
 * and treats camera permission as optional. If the user revoked the
 * camera permission we still allow the call to continue as audio-only.
 */
class HumandCallPermissionCheck(
    private val appContext: Context,
) : StreamPermissionCheck {

    override fun checkAndroidPermissions(context: Context, call: Call): Boolean {
        return checkAndroidPermissionsGroup(context, call).first
    }

    override fun checkAndroidPermissionsGroup(
        context: Context,
        call: Call,
    ): Pair<Boolean, Set<String>> {
        val missingPermissions = mutableSetOf<String>()
        val ownCapabilities = call.state.ownCapabilities.value

        val needsAudio = ownCapabilities.any { it is OwnCapability.SendAudio }
        if (needsAudio && !hasPermission(Manifest.permission.RECORD_AUDIO)) {
            missingPermissions.add(Manifest.permission.RECORD_AUDIO)
        }

        return Pair(missingPermissions.isEmpty(), missingPermissions)
    }

    private fun hasPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(appContext, permission) ==
            PackageManager.PERMISSION_GRANTED
    }
}
