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

import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.audio.record.screen.test.base.BaseActivity
import com.audio.record.screen.test.databinding.ActivityPlayBinding
import com.audio.record.screen.test.service.FloatingWindowBridge
import com.audio.record.screen.test.tool.Common


/**
 * Service悬浮窗中请求权限的透明Activity
 */
class ScreenPermissionActivity : AppCompatActivity() {

    private lateinit var screenCaptureLauncher: ActivityResultLauncher<Intent>

    //录音权限
    private lateinit var micLauncher: ActivityResultLauncher<String>
    companion object{

        const val key_with_audio="key_with_audio"
    }
    private var withAudio = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Common.setStatusBarTextColor(this, true)
        withAudio = intent.getBooleanExtra(key_with_audio, false)
        screenCaptureLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == RESULT_OK && result.data != null) {
                val data: Intent? = result.data
                FloatingWindowBridge.updateMediaProjection(result.resultCode, data!!)
            }
            finish()
        }

        micLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                Common.showLog("mic 权限授予")
                requestScreenPermission()
            } else {
                Common.showLog("mic 权限拒绝")
            }
        }
        if(withAudio){
            micLauncher.launch(android.Manifest.permission.RECORD_AUDIO)
        }else{
            requestScreenPermission()
        }
    }


    private fun requestScreenPermission() {
        val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val intent = mediaProjectionManager.createScreenCaptureIntent()
        screenCaptureLauncher.launch(intent)
    }



}