package com.example.firefly_go_android

import android.app.Activity
import android.os.Bundle
import android.util.Log
import de.robv.android.xposed.IXposedHookLoadPackage
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedHelpers
import de.robv.android.xposed.callbacks.XC_LoadPackage
import libandroid.Libandroid

class MainHook : IXposedHookLoadPackage {
    override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) {
        val pkg = lpparam.packageName
        if (!pkg.startsWith("com.miHoYo.hkrpg") && 
            !pkg.startsWith("com.HoYoverse.hkrpg") && 
            !pkg.startsWith("com.HoYoverse.Cyrene")
        ) return

        XposedHelpers.findAndHookMethod(
            Activity::class.java.name,
            lpparam.classLoader,
            "onCreate",
            Bundle::class.java,
            object : XC_MethodHook() {
                override fun afterHookedMethod(param: MethodHookParam) {
                    val activity = param.thisObject as Activity
                    Log.d("FireflyMod", "Đang mở Activity: ${activity.javaClass.name}")
                    FireflyModMenu.init(activity)
                }
            }
        )

        // Hook vào lúc Activity bị tắt
        XposedHelpers.findAndHookMethod(
            Activity::class.java.name,
            lpparam.classLoader,
            "onDestroy",
            object : XC_MethodHook() {
                override fun beforeHookedMethod(param: MethodHookParam) {
                    val activity = param.thisObject as Activity
                    val activityName = activity.javaClass.name

                    if (activity.isTaskRoot || activityName.contains("Unity")) {
                        Log.d("FireflyMod", "Main Game Activity ($activityName) đang đóng, tắt Server...")
                        try {
                            Libandroid.setServerRunning(false)
                        } catch (e: Exception) {
                            Log.e("FireflyMod", "Lỗi khi tự động tắt server: ${e.message}")
                        }
                    } else {
                        Log.d("FireflyMod", "Activity phụ ($activityName) đóng, bỏ qua không tắt Server.")
                    }
                }
            }
        )
    }
}