package com.example.defenseapplication.liveVideo

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaRecorder
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.ScaleAnimation
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import chuangyuan.ycj.videolibrary.video.ExoUserPlayer
import com.example.defenseapplication.R
import com.example.defenseapplication.base.BaseActivity
import com.example.defenseapplication.databinding.LiveVideoActivityBinding
import com.example.defenseapplication.utils.ActivityManager
import com.gyf.immersionbar.ImmersionBar
import java.io.File
import java.io.IOException
import android.content.res.Configuration
import androidx.activity.OnBackPressedCallback
import chuangyuan.ycj.videolibrary.listener.VideoInfoListener
import chuangyuan.ycj.videolibrary.video.VideoPlayerManager

private const val TAG = "LiveVideoActivity"
//智能防御机A1
class LiveVideoActivity : BaseActivity() {
    private lateinit var binding: LiveVideoActivityBinding

    private lateinit var exoPlayerManager: ExoUserPlayer
    private var isVoiceEnabled = false
    private var isLightOn = false
    private var isRecording = false
    private var mediaRecorder: MediaRecorder? = null
    private var micPulseAnimation: ScaleAnimation? = null
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            startRecordingMode()
        } else {
            Toast.makeText(this, R.string.recording_permission_needed, Toast.LENGTH_SHORT).show()
            isRecording = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = LiveVideoActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // ImmersionBar核心调用,沉浸式
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()

        val deviceName = intent.getStringExtra("device_name")
        if (!deviceName.isNullOrEmpty()) {
            binding.tvTitle.text = deviceName
        }

        // 初始化播放器
        initVideoPlayer()
        initListener()
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (exoPlayerManager.onBackPressed()) {
                    return
                }
                // 无全屏时执行默认返回逻辑（如 finish）
                finish()
            }
        })
    }
    private fun initVideoPlayer() {
        val videoPlayerView = binding.exoPlayContextId

        exoPlayerManager = VideoPlayerManager.Builder(VideoPlayerManager.TYPE_PLAY_GESTURE, videoPlayerView)
            .setPlayUri("https://media.w3.org/2010/05/sintel/trailer.mp4")//真实地址
            .setPosition(0)
            .addVideoInfoListener(object : VideoInfoListener {
                // 注意：此处的 p0: Long 是视频开始播放时的位置信息，可以按需使用
                override fun onPlayStart(p0: Long) {
                    Log.d(TAG, "视频开始播放")
                }

                override fun onLoadingChanged() {
                    // 视频加载状态变化
                }

                override fun onPlayerError(p0: com.google.android.exoplayer2.ExoPlaybackException?) {
                    Toast.makeText(this@LiveVideoActivity, "播放失败", Toast.LENGTH_SHORT).show()
                }

                override fun onPlayEnd() {
                    Log.d(TAG, "播放结束")
                }

                // 修正点：库的接口要求必须实现 isPlaying 方法
                override fun isPlaying(p0: Boolean) {
                    // p0 表示当前是否正在播放
                }

                fun onRepeatModeChanged(p0: Int) {
                    // 循环模式改变时的回调
                }
            })
            .create()

        exoPlayerManager.startPlayer()
    }

    private fun initListener() {
        binding.btnBack.setOnClickListener {
            ActivityManager.finishExceptHome()
            val intent = Intent(this, com.example.defenseapplication.home.HomeActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            startActivity(intent)
            finish()
        }

        binding.ivMenu.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
        binding.llVoice.setOnClickListener {
            toggleVoice()
        }

        binding.llLight.setOnClickListener {
            toggleLight()
        }

        binding.llRecord.setOnClickListener {
            toggleRecording()
        }

        binding.llAlarmLog.setOnClickListener {
            Toast.makeText(this, R.string.view_alarm_log, Toast.LENGTH_SHORT).show()
        }

        // 点击xq箭头跳转到AlarmLogActivity
        binding.xq.setOnClickListener {
            val intent = Intent(this, AlarmLogActivity::class.java)
            startActivity(intent)
        }
    }


    private fun toggleVoice() {
        isVoiceEnabled = !isVoiceEnabled
        
        if (isVoiceEnabled) {
            binding.ivVoice.setImageResource(com.example.defenseapplication.R.drawable.voice_on_open)
            Toast.makeText(this, R.string.sound_on, Toast.LENGTH_SHORT).show()
        } else {
            binding.ivVoice.setImageResource(com.example.defenseapplication.R.drawable.voice)
            Toast.makeText(this, R.string.sound_off, Toast.LENGTH_SHORT).show()
        }
    }

    private fun toggleLight() {
        isLightOn = !isLightOn
        
        if (isLightOn) {
            binding.ivLight.setImageResource(com.example.defenseapplication.R.drawable.light_on_open)
            Toast.makeText(this, R.string.light_on, Toast.LENGTH_SHORT).show()
        } else {
            binding.ivLight.setImageResource(com.example.defenseapplication.R.drawable.light_on)
            Toast.makeText(this, R.string.light_off, Toast.LENGTH_SHORT).show()
        }
    }

    private fun toggleRecording() {
        if (!isRecording) {
            if (checkRecordAudioPermission()) {
                startRecordingMode()
            } else {
                requestRecordAudioPermission()
            }
        } else {
            stopRecordingMode()
        }
    }
    
    private fun checkRecordAudioPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    private fun requestRecordAudioPermission() {
        requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
    }
    
    private fun startRecordingMode() {
        isRecording = true
        
        binding.ivRecord.setImageResource(com.example.defenseapplication.R.drawable.copy_open)
        // 隐藏告警日志区域，显示控制台区域
        binding.llAlarmLog.visibility = View.GONE
        binding.consoleBar.visibility = View.VISIBLE
        
        // 麦克风切换成开启状态
        binding.ivVoice.setImageResource(com.example.defenseapplication.R.drawable.voice_on_open)
        isVoiceEnabled = true
        
        // 启动语音录制
        startVoiceRecording()
        
        // 启动麦克风脉冲动画
        //startMicPulseAnimation()
        
        Toast.makeText(this, R.string.start_control_mode, Toast.LENGTH_SHORT).show()
    }
    
    private fun stopRecordingMode() {
        isRecording = false
        
        binding.ivRecord.setImageResource(com.example.defenseapplication.R.drawable.copy)
        // 显示告警日志区域，隐藏控制台区域
        binding.llAlarmLog.visibility = View.VISIBLE
        binding.consoleBar.visibility = View.GONE
        
        // 麦克风切换成关闭状态
        binding.ivVoice.setImageResource(com.example.defenseapplication.R.drawable.voice)
        isVoiceEnabled = false
        
        // 停止语音录制
        stopVoiceRecording()
        
        // 停止麦克风脉冲动画
        stopMicPulseAnimation()
        
        Toast.makeText(this, R.string.stop_control_mode, Toast.LENGTH_SHORT).show()
    }


    private fun stopMicPulseAnimation() {
        micPulseAnimation?.let {
            binding.ivVoice.clearAnimation()
            micPulseAnimation = null
        }
    }

    private fun startVoiceRecording() {
        mediaRecorder = MediaRecorder().apply {
            setAudioSource(MediaRecorder.AudioSource.MIC)
            setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
            val outputDir = getExternalFilesDir(null) ?: filesDir
            val audioDir = File(outputDir, "audio")
            if (!audioDir.exists()) {
                audioDir.mkdirs()
            }
            val outputFile = File(audioDir, "voice_record_${System.currentTimeMillis()}.3gp")
            setOutputFile(outputFile.absolutePath)
            setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
            
            try {
                prepare()
                start()
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(this@LiveVideoActivity, R.string.recording_start_failed, Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun stopVoiceRecording() {
        mediaRecorder?.let {
            try {
                it.stop()
                it.release()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            mediaRecorder = null
        }
    }
    override fun onResume() {
        super.onResume()
        exoPlayerManager.onResume()
    }

    override fun onPause() {
        super.onPause()
        exoPlayerManager.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        exoPlayerManager.onDestroy()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        // 横竖屏切换时通知播放器
        exoPlayerManager.onConfigurationChanged(newConfig)
    }

}

