package com.smplayer.smplayer

import android.content.res.Configuration
import android.media.AudioManager
import android.os.Bundle
import android.view.KeyEvent
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine

class MainActivity : FlutterActivity() {
    private var systemAudio: SystemAudioBridge? = null
    private var pipBridge: PipBridge? = null
    private var apkInstaller: ApkInstallerBridge? = null
    private var androidTls: AndroidTlsBridge? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        systemAudio = SystemAudioBridge(applicationContext, flutterEngine)
        pipBridge = PipBridge(this, flutterEngine)
        apkInstaller = ApkInstallerBridge(applicationContext, flutterEngine)
        androidTls = AndroidTlsBridge(applicationContext, flutterEngine)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        volumeControlStream = AudioManager.STREAM_MUSIC
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        val bridge = systemAudio
        if (bridge != null && bridge.keyInterceptEnabled) {
            val isVolumeUp = event.keyCode == KeyEvent.KEYCODE_VOLUME_UP
            val isVolumeDown = event.keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
            if (isVolumeUp || isVolumeDown) {
                if (event.action == KeyEvent.ACTION_DOWN) {
                    bridge.adjustVolume(
                        if (isVolumeUp) 1 else -1,
                        showSystemUi = false,
                    )
                }
                return true
            }
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onUserLeaveHint() {
        super.onUserLeaveHint()
        pipBridge?.onUserLeaveHint()
    }

    override fun onPictureInPictureModeChanged(
        isInPictureInPictureMode: Boolean,
        newConfig: Configuration,
    ) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
        pipBridge?.onPipModeChanged(isInPictureInPictureMode)
    }

    override fun onDestroy() {
        pipBridge?.dispose()
        pipBridge = null
        apkInstaller?.dispose()
        apkInstaller = null
        androidTls?.dispose()
        androidTls = null
        systemAudio?.dispose()
        systemAudio = null
        super.onDestroy()
    }
}
