package com.ydl.confide.home

import android.Manifest
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.ydl.audioim.api.IAudioImService
import com.ydl.confide.R
import com.ydl.confide.databinding.DialogConfidePermissionBinding
import com.ydl.ydlcommon.modular.findRouteService

class ConfidePermissionDialog : DialogFragment() {

    var callback: ((Boolean) -> Unit)? = null

    private lateinit var binding: DialogConfidePermissionBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val granted = PermissionUtils.isGranted(Manifest.permission.RECORD_AUDIO)
        if (granted) {
            callback?.invoke(true)
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.dialog_confide_permission, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.ivClose.setOnClickListener {
            reject()
        }

        binding.tvBtn.setOnClickListener {
            PermissionUtils
                .permission(PermissionConstants.MICROPHONE)
                .callback(object : PermissionUtils.FullCallback {
                    override fun onGranted(permissionsGranted: MutableList<String>?) {
                        callback?.invoke(true)
                        dismissAllowingStateLoss()
                    }

                    override fun onDenied(permissionsDeniedForever: MutableList<String>?, permissionsDenied: MutableList<String>?) {
                        reject()
                    }
                }).request()
        }
    }

    private fun reject() {
        dismissAllowingStateLoss()
//        CommonDialog(context)
//            .setMessage("由于您尚未同意获取麦克风权限，本次通话将使用传统电话方式拨打")
//            .setRightClick("确定") {
//                callback?.invoke(false)
//            }
//            .setCancelAble(false)
//            .show()
        findRouteService(IAudioImService::class.java).openPermissionRejectDialog(activity) { callback?.invoke(false) }
    }

    override fun onStart() {
        super.onStart()
        isCancelable = false
        val width = (resources.displayMetrics.widthPixels * 0.85).toInt()
        dialog?.window?.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT)
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    }
}