package com.eventtan.test.penguin_flutter_sample.PermissionManager

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class PermissionManager(
    private val context: Context,
     val listener: PermissionListener,
    private val requestCode: Int,
    vararg permissions: String
) {

    private val permissionsArray = permissions

    interface PermissionListener {
        fun onPermissionGranted()
        fun onPermissionDenied()
    }

    fun arePermissionsGranted(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionsArray.all {
                ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
            }
        } else {
            true
        }
    }

    fun requestPermissions(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(activity, permissionsArray, requestCode)
        }
    }

    fun handlePermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (this.requestCode == requestCode) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                listener.onPermissionGranted()
            } else {
                listener.onPermissionDenied()
            }
        }
    }
}