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

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.LayoutInflater
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.marginBottom
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.audio.record.screen.test.R
import com.audio.record.screen.test.adapter.ViewPager2Adapter
import com.audio.record.screen.test.base.BaseActivity
import com.audio.record.screen.test.databinding.ActivityMain1Binding
import com.audio.record.screen.test.dialog.DialogPermission
import com.audio.record.screen.test.fragment.MainFragment
import com.audio.record.screen.test.service.ConnectionListener
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.Extend.setMarginBottom
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 com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator


class MainActivity1 : BaseActivity<ActivityMain1Binding>(), ConnectionListener,FloatingCallback {
    private lateinit var viewModel: MainViewModel
    private var isNotification = false
    private var isOverlay = false
    private lateinit var requestStoragePermission: ActivityResultLauncher<String>
    private lateinit var requestNotificationLauncher: ActivityResultLauncher<String>
    private var mPermissionDialog: DialogPermission? = null

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

    override fun onSetViewBefore() {
        super.onSetViewBefore()
//        val navigationBarHeight = Common.getNavigationBarHeight(this)
        Common.setNavigation(binding.tabLayout)
    }
    override fun initBinding(): ActivityMain1Binding = ActivityMain1Binding.inflate(layoutInflater)
    override fun onInitPadding(): Boolean = false
    override fun getFullColor(): Boolean = true
    override fun onCreateInit() {
        mediaProjectionManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        bingVp()
        initLauncher()
        firstCheck()
        checkStoragePermissionAndDoSomething()
    }

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

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


//        screenCaptureLauncher = registerForActivityResult(
//            ActivityResultContracts.StartActivityForResult()
//        ) { result ->
//            if (result.resultCode == Activity.RESULT_OK) {
//                val data: Intent? = result.data
//                val mediaProjection =
//                    mediaProjectionManager.getMediaProjection(result.resultCode, data!!)
//                ScreenCaptureHelper.startScreenCapture(this, mediaProjection)
//            } 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("已获取存储权限")
            showPermissionDialog()
        }
    }

    private fun bingVp() {
        val tabIcons =
            intArrayOf(R.drawable.tab1_selector, R.drawable.tab2_selector)
        binding.run {
            viewPager2.isUserInputEnabled = false
            viewPager2.adapter = ViewPager2Adapter(this@MainActivity1)
            TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
                val customView =
                    LayoutInflater.from(this@MainActivity1).inflate(R.layout.tab_item, null)
                val icon = customView.findViewById<ImageView>(R.id.tab_icon)

                if (position in tabIcons.indices) {
                    icon.setImageResource(tabIcons[position])
                }
                icon.isSelected = position == 0
                tab.customView = customView
            }.attach()
            tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    tab?.customView?.run {
                        findViewById<ImageView>(R.id.tab_icon).isSelected = true
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    tab?.customView?.run {
                        findViewById<ImageView>(R.id.tab_icon).isSelected = false
                    }
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })
        }
    }

    private fun showPermissionDialog() {
        if (isNotification && isOverlay) {
            return
        }
        mPermissionDialog = mPermissionDialog ?: DialogPermission {
            when (it) {
                DialogPermission.type_ball -> {
                    intentSysWindow(this@MainActivity1)
                }

                DialogPermission.type_notification -> {
                    requestNotificationLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
                }
            }
        }
        mPermissionDialog?.show(supportFragmentManager, "")
    }


    //悬浮窗
    private fun intentSysWindow(context: Context) {
        val intent = Intent(
            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
            Uri.parse("package:${context.packageName}")
        )
        startActivity(intent)
    }

    //检查通知和悬浮窗是否已经enable
    private fun firstCheck() {
        Permission.checkNotification(this@MainActivity1) {
            isNotification = it
            if (it) {
                startForegroundService()
            }
        }
        Permission.checkOvalApp(this@MainActivity1) {
            isOverlay = it
        }

    }

    private fun startForegroundService() {
        FloatingWindowBridge.startAndBindService(this@MainActivity1)
        FloatingWindowBridge.addListener(this)
    }

    override fun onStartRecording() {
        this@MainActivity1.moveTaskToBack(true)

    }
    override fun onResume() {
        super.onResume()
        //初始进程中，在桌面回到Activity的时候更新当前录制状态
        FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_sync_recording_status)
    }
    override fun onServiceConnected() {
        viewModel.updateServiceConnectStatus(true)
        FloatingWindowBridge.registerCallback(this)
        //新开进程的时候检测当前悬浮窗状态，刷新当前各ImageView状态
        FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_sync_view_status)
        FloatingWindowBridge.sendCommand(FloatingWindowBridge.COMMEND_sync_recording_status)
    }

    override fun onRefreshViewShow(
        webCamShow: Boolean,
        screenshotShow: Boolean,
        ballShow: Boolean
    ) {
        super.onRefreshViewShow(webCamShow, screenshotShow, ballShow)
        Common.showLog(" 收到onRefreshViewShow webCamShow=${webCamShow}  screenshotShow=${screenshotShow} ballShow=${ballShow}")
        viewModel.updateWebcamStatus(webCamShow)
        viewModel.updateScreenshotStatus(screenshotShow)
        viewModel.updateBallStatus(ballShow)
    }
    override fun onRefreshRecordingStatus(status: Int) {
        super.onRefreshRecordingStatus(status)
        viewModel.updateRecordingStatus(status)
    }



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