package com.audio.record.screen.test.fragment.child

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.audio.record.screen.test.R
import com.audio.record.screen.test.base.BaseFragment
import com.audio.record.screen.test.databinding.FragmentRecordNormalBinding
import com.audio.record.screen.test.dialog.DialogAudio
import com.audio.record.screen.test.dialog.DialogPermission
import com.audio.record.screen.test.service.FloatingCallback
import com.audio.record.screen.test.service.FloatingWindowBridge
import com.audio.record.screen.test.tool.Common
import com.audio.record.screen.test.tool.ConstValue
import com.audio.record.screen.test.tool.Permission
import com.audio.record.screen.test.tool.ScreenCaptureHelper
import com.audio.record.screen.test.viewmodel.MainViewModel
import com.audio.record.screen.test.viewmodel.PreviewViewModel
import kotlinx.coroutines.launch


class RecordNormalFragment : BaseFragment<FragmentRecordNormalBinding>(), FloatingCallback {

    private lateinit var navController: NavController

    private lateinit var viewModel: MainViewModel
    private lateinit var mediaProjectionManager: MediaProjectionManager

    //摄像头
    private lateinit var cameraLauncher: ActivityResultLauncher<String>

    //截屏
//    private lateinit var screenCaptureLauncher: ActivityResultLauncher<Intent>

    //录制
    private lateinit var recorderLauncher: ActivityResultLauncher<Intent>

    //录音权限
    private lateinit var micPermissionLauncher: ActivityResultLauncher<String>

    private var mAudioDialog: DialogAudio? = null

    //是否带音频录制
    private var isWithAudio = false


    private var pendingType: Int = -1
    private val key_type = "check_type"
    override fun initBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentRecordNormalBinding = FragmentRecordNormalBinding.inflate(inflater, container, false)


    companion object {
        @JvmStatic
        fun newInstance() = RecordNormalFragment()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mediaProjectionManager =
            requireActivity().getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        viewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        initClick()
        initLauncher()

        viewModel.serviceConnectStatus.observe(requireActivity()) {
            FloatingWindowBridge.registerCallback(this)
        }
        viewModel.ballStatus.observe(requireActivity()) {
            binding.btnFloatingBall.isSelected = it
            setBall(it)

        }
        viewModel.screenshotStatus.observe(requireActivity()) {
            binding.btnScreenshot.isSelected = it
            setScreenshot(it)
        }
        viewModel.webcamStatus.observe(requireActivity()) {
            binding.btnWebcam.isSelected = it
            setWebcam(it)
        }
        viewModel.navController.observe(requireActivity()){
            navController = it
        }

    }





    private fun initLauncher() {
        cameraLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_camera)
                Common.showLog("CAMERA 权限授予")
            } else {
                // TODO:
                Common.showLog("CAMERA 权限拒绝")
            }
        }

        recorderLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK && result.data != null) {
                    val intent = result.data
                    val resultCode = result.resultCode
                    FloatingWindowBridge.updateMediaProjection(result.resultCode, intent!!)
                    when(pendingType){
                        ConstValue.type_record->{ startCountDown()}
                        ConstValue.type_show_screenshot->{
                            FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_screenshot)
                        }
                    }

                } else {
                    Common.showLog("录屏授权失败 ")
                }
            }


        micPermissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                Common.showLog("mic 权限授予")
                startRecorder()
            } else {
                Common.showLog("mic 权限拒绝")
            }
        }

    }

    private fun initClick() {
        binding.run {
            btnWebcam.setOnClickListener {
                it.isSelected = !it.isSelected
                it.isSelected.let { currentStatus ->
                    viewModel.updateWebcamStatus(currentStatus)
                }

            }
            btnScreenshot.setOnClickListener {
                it.isSelected = !it.isSelected

                it.isSelected.let { currentStatus ->
                    viewModel.updateScreenshotStatus(currentStatus)
                }

            }
            btnFloatingBall.setOnClickListener {
                it.isSelected = !it.isSelected

                it.isSelected.let { currentStatus ->
                    viewModel.updateBallStatus(currentStatus)
                }
            }
            btnRecorder.setOnClickListener {
                showAudioDialog()
            }
        }

    }

    private fun setWebcam(boolean: Boolean) {
        if (boolean) {
            Permission.checkCamera(requireContext()) { openCamera ->
                if (openCamera) {
                    FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_camera)
                } else {
                    cameraLauncher.launch(android.Manifest.permission.CAMERA)
                }
            }

        } else {
            FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_hide_camera)
        }
    }

    private fun setScreenshot(boolean: Boolean) {
        if (boolean) {
            requestRecordPermission(ConstValue.type_show_screenshot){
                FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_screenshot)
            }

        } else {
            FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_hide_screenshot)
        }
    }

    private fun setBall(boolean: Boolean) {
        if (boolean) {
            FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_ball)
        } else {
            FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_hide_ball)
        }
    }

    private fun startRecorder() {
        requestRecordPermission( ConstValue.type_record){
            startCountDown()
        }
    }


    /**
     * 请求录屏权限
     */
    private fun requestRecordPermission(type:Int,check:(()->Unit)? = null){
        // TODO:  requestRecordPermission
        if (FloatingWindowBridge.getMediaProjection() == null) {
            val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
            pendingType = type
            recorderLauncher.launch(captureIntent)
        }else{
            check?.invoke()
        }
    }



    private fun showAudioDialog() {
        mAudioDialog = mAudioDialog ?: DialogAudio {
            when (it) {
                DialogAudio.type_with_audio -> {
                    isWithAudio = true
                    micPermissionLauncher.launch(android.Manifest.permission.RECORD_AUDIO)
                }

                DialogAudio.type_without_audio -> {
                    isWithAudio = false
                    startRecorder()
                }
            }
        }
        mAudioDialog?.show(childFragmentManager, "")
    }

    private fun startCountDown() {
        FloatingWindowBridge.updateAudio(isWithAudio)
        val arrayOf = arrayOf("3", "2", "1")
        FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_show_countdown, arrayOf)
    }

    override fun onStartRecording() {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            navController.navigate(R.id.action_to_recording)
            Common.showLog(" FragmentRecordNormal  回调  onStartRecording 执行111111111")
        }

//        else {
//            // 延迟执行
//            lifecycleScope.launch {
//                lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
//                    Common.showLog(" FragmentRecordNormal  回调  onStartRecording 延迟执行 11111111")
//                    navController.navigate(R.id.action_to_recording)
//                }
//            }
//        }
    }



    override fun onDestroy() {
        super.onDestroy()
        FloatingWindowBridge.unregisterCallback(this)
    }

}