package com.lazy.emulate

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.KeyEvent
import android.view.MotionEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.navigation.compose.rememberNavController
import com.lazy.emulate.data.PreferencesManager
import com.lazy.emulate.data.repository.GameRepository
import com.lazy.emulate.emulation.EmulationEngine
import com.lazy.emulate.input.ButtonMappingManager
import com.lazy.emulate.input.ControllerManager
import com.lazy.emulate.ui.navigation.EmulateNavGraph
import com.lazy.emulate.ui.theme.EmulateTheme

class MainActivity : ComponentActivity() {

    private lateinit var controllerManager: ControllerManager
    private lateinit var gameRepository: GameRepository
    lateinit var preferencesManager: PreferencesManager
        private set
    lateinit var buttonMappingManager: ButtonMappingManager
        private set

    @OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        requestAllFilesPermission()

        preferencesManager = PreferencesManager(this)
        buttonMappingManager = ButtonMappingManager(preferencesManager)
        controllerManager = ControllerManager(this, buttonMappingManager)
        gameRepository = GameRepository(this)
        EmulationEngine.buttonMappingManager = buttonMappingManager

        setContent {
            EmulateTheme {
                val windowSizeClass = calculateWindowSizeClass(this)
                val navController = rememberNavController()

                EmulateNavGraph(
                    navController = navController,
                    windowSizeClass = windowSizeClass,
                    gameRepository = gameRepository,
                    controllerManager = controllerManager,
                    preferencesManager = preferencesManager,
                    buttonMappingManager = buttonMappingManager
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        controllerManager.start()
        if (Environment.isExternalStorageManager()) {
            gameRepository.scanGameFolders()
        }
    }

    override fun onPause() {
        super.onPause()
        controllerManager.stop()
    }

    private fun requestAllFilesPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            val intent = Intent(
                Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                Uri.parse("package:$packageName")
            )
            startActivity(intent)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event != null && controllerManager.handleKeyEvent(event)) return true
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (event != null && controllerManager.handleKeyEvent(event)) return true
        return super.onKeyUp(keyCode, event)
    }

    override fun onGenericMotionEvent(event: MotionEvent?): Boolean {
        if (event != null && controllerManager.handleMotionEvent(event)) return true
        return super.onGenericMotionEvent(event)
    }
}
