package com.cartrack.cartrackble

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class PermissionManager(private val activity: Activity) {

    private val permissionRequired =
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            listOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
            )
        } else {
            listOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
            )
        }

    fun requestPermission(): Boolean {
        val permissionStatus =
            permissionRequired.map { ContextCompat.checkSelfPermission(activity, it) }

        ActivityCompat.requestPermissions(activity, permissionRequired.toTypedArray(), 10)
        return isPermissionGranted(permissionStatus)
    }

    fun isPermissionGranted(grantResults: List<Int>): Boolean {
        return grantResults
            .map { it == PackageManager.PERMISSION_GRANTED }
            .reduce { acc, isGranted -> acc && isGranted }
    }
}