package com.bassbooster.soundeffects.equalizer.view.activity.setting.permissions

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

import com.bassbooster.equalizer.R
import com.bassbooster.equalizer.databinding.ActivityPermissionsBinding
import com.bassbooster.soundeffects.equalizer.utils.AppUtils

@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.M)

class PermissionsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityPermissionsBinding
    private val RECORD_AUDIO_PERMISSION_CODE = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPermissionsBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        AppUtils.hideNavigationBar(this)

        binding.imgBackPermissions.setOnClickListener {
            finish()
        }
//        setOnEvent()
    }

    override fun onResume() {
        super.onResume()
        AppUtils.hideNavigationBar(this)
    }

    @SuppressLint("NewApi")
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            AppUtils.hideNavigationBar(this)
        }
    }
//    override fun onResume() {
//        super.onResume()
//        binding.imgSCMicro.isChecked = ContextCompat.checkSelfPermission(
//            this,
//            Manifest.permission.RECORD_AUDIO
//        ) == PackageManager.PERMISSION_GRANTED
//
//        binding.imgSCFloating.isChecked =
//            !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this))
//    }

    private fun setOnEvent() {
        binding.imgBackPermissions.setOnClickListener {
            finish()
        }
        binding.imgSCMicro.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.RECORD_AUDIO),
                        RECORD_AUDIO_PERMISSION_CODE
                    )
                }
            } else {
                showPermissionSettingDialog(
                    R.string.turn_off_microphone_access,
                    R.string.you_want_to_revoke_permission,
                    R.string.setting,
                    R.string.cancel
                )

            }
        }
        binding.imgSCFloating.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {

                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }

            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
                    showFloatingPermissionSettingDialog(
                        R.string.turn_off_floating_window,
                        R.string.you_have_denied,
                        R.string.setting,
                        R.string.cancel
                    )
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == RECORD_AUDIO_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("LOG", "was granted: ")
            } else {
                if (!shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
                    showPermissionSettingDialog(
                        R.string.permission_denied,
                        R.string.you_have_denied,
                        R.string.setting,
                        R.string.cancel
                    )
                }
            }
        }
    }

    private fun showPermissionSettingDialog(
        tvTitle: Int,
        tvBody: Int,
        tvSetting: Int,
        tvCancel: Int
    ) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle(getColoredText(tvTitle, Color.WHITE))
            .setMessage(getColoredText(tvBody, Color.WHITE))
            .setPositiveButton(getColoredText(tvSetting, Color.WHITE)) { dialog, which ->

                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
            .setNegativeButton(getColoredText(tvCancel, Color.WHITE)) { dialog, which ->

                recreate()
            }
            .setCancelable(false)

        val dialog = builder.create()
        dialog.window?.setBackgroundDrawableResource(R.drawable.custom_dialog)
        dialog.show()
    }

    private fun getColoredText(stringResId: Int, color: Int): CharSequence {
        val text = getString(stringResId)
        val spannableString = SpannableString(text)
        val colorSpan = ForegroundColorSpan(color)
        spannableString.setSpan(colorSpan, 0, text.length, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannableString
    }

    private fun showFloatingPermissionSettingDialog(
        tvTitle: Int,
        tvBody: Int,
        tvSetting: Int,
        tvCancel: Int
    ) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle(getColoredText(tvTitle, Color.WHITE))
            .setMessage(getColoredText(tvBody, Color.WHITE))
            .setPositiveButton(getColoredText(tvSetting, Color.WHITE)) { dialog, which ->

                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
            .setNegativeButton(getColoredText(tvCancel, Color.WHITE)) { dialog, which ->
                recreate()
            }
            .setCancelable(false)

        val dialog = builder.create()
        dialog.window?.setBackgroundDrawableResource(R.drawable.custom_dialog)
        dialog.show()
    }
}

