package com.audio.record.screen.test.activity

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.display.DisplayManager
import android.media.MediaRecorder
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.audio.record.screen.test.base.BaseActivity
import com.audio.record.screen.test.databinding.ActivityMainBinding
import com.audio.record.screen.test.service.FloatingWindowBridge
import com.audio.record.screen.test.tool.Common
import com.audio.record.screen.test.tool.ScreenCaptureHelper
import com.audio.record.screen.test.tool.VideoFileHelper

class MainActivity : BaseActivity<ActivityMainBinding>() {
    val NOTIFICATION_PERMISSION_REQUEST_CODE = 123
    val SCREEN_CAPTURE_REQUEST_CODE = 124
    val REQUEST_SCREENSHOT = 125

    lateinit var requestPermissionLauncher: ActivityResultLauncher<String>
    lateinit var micPermissionLauncher: ActivityResultLauncher<String>
    lateinit var cameraPermissionLauncher: ActivityResultLauncher<String>
    lateinit var requestStoragePermission: ActivityResultLauncher<String>

    lateinit var mediaProjectionManager: MediaProjectionManager
//    private var floatingService: ScreenRecordService? = null

    private lateinit var  tmpVideoUri:Uri

//    private val connection = object : ServiceConnection {
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            val binder = service as ScreenRecordService.FloatingBinder
//            floatingService = binder.getService()
//            binder.setCallback(object : FloatingCallback {
//                override fun onFloatingButtonClicked(action: String) {
//                    // 处理来自悬浮窗的点击
//                    when (action) {
//                        "stop_clicked" -> {
//
//                        }
//                    }
//                }
//            })
//        }
//
//        override fun onServiceDisconnected(name: ComponentName?) {
//            floatingService = null
//        }
//    }


    override fun initBinding(): ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)

    override fun getFullColor(): Boolean? = true

    override fun onCreateInit() {
        initPermissionLauncher()
//        checkSyswindow(this@MainActivity)
        checkStoragePermissionAndDoSomething()


        binding.btn1.setOnClickListener {
            requestNotification()
        }
        binding.btn2.setOnClickListener {
            checkStoragePermissionAndDoSomething()
        }
        binding.btn3.setOnClickListener {
            micPermissionLauncher.launch(android.Manifest.permission.RECORD_AUDIO)
        }
        binding.btn4.setOnClickListener {
            checkCamera()
        }
        binding.btnShowcamera.setOnClickListener {
            it.isSelected = !it.isSelected
            if(it.isSelected){
                FloatingWindowBridge.sendCommand("show")
            }else{
                FloatingWindowBridge.sendCommand("hide")
            }

        }
        binding.btn7.setOnClickListener {
            startActivity(Intent(this,PreviewActivity::class.java))

        }

        mediaProjectionManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        binding.btn5.setOnClickListener {
            startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), SCREEN_CAPTURE_REQUEST_CODE)
        }
        binding.btn6.setOnClickListener {
            stopRecording()
        }

        binding.btnScreenshot.setOnClickListener {

            startActivityForResult( mediaProjectionManager.createScreenCaptureIntent(), REQUEST_SCREENSHOT)
        }
    }

    override fun onInitPadding(): Boolean  = true


    private fun initPermissionLauncher() {
        requestPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                if (isGranted) {
                    startForegroundService()
                    Common.showLog("权限授予")
                } else {
                    Common.showLog("权限拒绝")
                }
            }

        micPermissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                Common.showLog("mic 权限授予")
            } else {
                Common.showLog("mic 权限拒绝")
            }
        }
        cameraPermissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                Common.showLog("CAMERA 权限授予")
            } else {
                Common.showLog("CAMERA 权限拒绝")
            }
        }
        requestStoragePermission = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                // 权限已授予
                Common.showLog("已获取存储权限")
                // 执行写入文件操作
            } else {
                Common.showLog( "存储权限被拒绝" )
            }
        }


    }
    fun checkStoragePermissionAndDoSomething() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestStoragePermission.launch(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
        } else {
            // Android 10+ 不需要写权限，或者权限已获取
            // 执行写入文件操作
            Common.showLog("已获取存储权限")
        }
    }

    private fun checkSyswindow(context: Context) {
        if (!Settings.canDrawOverlays(context)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:${context.packageName}")
            )
            startActivity(intent)
        }

    }


    private fun requestNotification() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.POST_NOTIFICATIONS
                )
                != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
            } else {
                // 权限已授予，可以发送通知
                Common.showLog("权限已授予，可以发送通知")
                startForegroundService()
            }
        } else {
            // Android 12 及以下，不需要请求权限
            Common.showLog("不需要请求权限")
            startForegroundService()
        }
    }


    private fun checkCamera() {
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.CAMERA
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            cameraPermissionLauncher.launch(android.Manifest.permission.CAMERA)
        } else {
            Common.showLog("权限已授予 CAMERA")

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data!!)
        if (requestCode == SCREEN_CAPTURE_REQUEST_CODE && resultCode == RESULT_OK) {

            startRecording(mediaProjection)
        }else    if (requestCode == REQUEST_SCREENSHOT && resultCode == RESULT_OK && data != null) {
//            ScreenCaptureHelper.startScreenCapture(this,mediaProjection)
        }
    }

    private fun startForegroundService() {
//        FloatingWindowBridge.startAndBindService(this)
    }

    fun startRecording(mediaProjection: MediaProjection) {
        val screen = VideoFileHelper.getScreenInfo(this@MainActivity)
        val width = VideoFileHelper.alignTo16(screen.width)
        val height = VideoFileHelper.alignTo16(screen.height)
        initRecorder(width, height)
        mediaRecorder.start()

        val virtualDisplay = mediaProjection.createVirtualDisplay(
            "ScreenRecord",
            width, height, resources.displayMetrics.densityDpi,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mediaRecorder.surface, null, null
        )
    }

    fun stopRecording() {
        Common.showLog("-------录屏完成.....")
        mediaRecorder.stop()
        mediaRecorder.reset()
    }


    private lateinit var mediaRecorder: MediaRecorder

    fun initRecorder(width: Int, height: Int) {

        val (videoUri, pfd) = VideoFileHelper.createVideoFile(this, Common.folderName)
        tmpVideoUri = videoUri

        mediaRecorder = MediaRecorder().apply {
            setAudioSource(MediaRecorder.AudioSource.MIC)
            setVideoSource(MediaRecorder.VideoSource.SURFACE)
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            setOutputFile(pfd?.fileDescriptor)
            setVideoSize(width, height)
            setVideoEncoder(MediaRecorder.VideoEncoder.H264)
            setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            setVideoEncodingBitRate(8 * 1000 * 1000)
            setVideoFrameRate(30)
            prepare()
        }
    }

    override fun onDestroy() {
        super.onDestroy()

    }





}