package com.example.watch

import android.content.Intent
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSuggestion
import android.os.BatteryManager
import android.os.Build
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.content.Context
import android.net.ConnectivityManager

class MainActivity : FlutterActivity() {
    private val channel = "com.example.watch/launcher"
    private lateinit var connectivityManager: ConnectivityManager

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel)
            .setMethodCallHandler { call, result ->
                when (call.method) {

                    // ── Launcher ──────────────────────────────────────────
                    "openHomeSettings" -> {
                        try {
                            startActivity(
                                Intent(Settings.ACTION_HOME_SETTINGS)
                                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            )
                            result.success(null)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", e.message, null)
                        }
                    }

                    // ── Battery ───────────────────────────────────────────
                    "getBatteryInfo" -> {
                        try {
                            val bm = getSystemService(BATTERY_SERVICE) as BatteryManager
                            val level = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
                            val isCharging = bm.isCharging
                            result.success(mapOf("level" to level, "isCharging" to isCharging))
                        } catch (e: Exception) {
                            result.error("ERROR", e.message, null)
                        }
                    }

                    // ── Internet (WiFi + mobile data panel) ───────────────
                    "openInternetSettings" -> {
                        try {
                            val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
                            } else {
                                Intent(Settings.ACTION_WIRELESS_SETTINGS)
                            }
                            startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
                            result.success(null)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", e.message, null)
                        }
                    }

                    // ── Mobile Data Toggle ───────────────────────────────
                    "toggleMobileData" -> {
                        val enable = call.argument<Boolean>("enable")
                        if (enable != null) {
                            setMobileDataState(enable)
                            result.success(null)
                        } else {
                            result.error("INVALID_ARGUMENT", "Enable status not provided", null)
                        }
                    }
                    "getMobileDataStatus" -> {
                        val isEnabled = isMobileDataEnabled()
                        result.success(isEnabled)
                    }

                    // ── Accessibility Settings ───────────────────────────────
                    "openAccessibilitySettings" -> {
                        try {
                            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                            startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
                            result.success(null)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", e.message, null)
                        }
                    }

                    // ── SystemSettings ───────────────────────────────
                    "openSystemSettings" -> {
                        try {
                            val intent = packageManager.getLaunchIntentForPackage("com.dw.setting")
                            startActivity(intent)
                            result.success(true)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", "تنظیمات باز نشد", null)
                        }
                    }

                    // ── EngineerMode ───────────────────────────────
                    "openEngineerMode" -> {
                        try {
                            // ساخت اینتنت برای باز کردن اکتیویتی مهندسی
                            val intent = Intent().apply {
                                // تنظیم پکیج و کلاس دقیق که فرستادید
                                setClassName("com.sprd.engineermode", "com.sprd.engineermode.EngineerModeActivity")
                                // اضافه کردن فلگ برای شروع اکتیویتی جدید در صورت نیاز
                                // flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            }
                            startActivity(intent)
                            result.success(true)
                        } catch (e: Exception) {
                            // اگر اپلیکیشن نصب نباشد یا خطایی رخ دهد
                            result.error("ERROR", "خطا در باز کردن EngineerMode: ${e.message}", null)
                        }
                    }

                    // ── Dialer ───────────────────────────────
                    "openDialer" -> {
                        try {
                            val intent = packageManager.getLaunchIntentForPackage("com.divo.phone")
                            startActivity(intent)
                            result.success(true)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", "شماره‌گیر در دسترس نیست", null)
                        }
                    }

                    // ── bluetooth ───────────────────────────────
                    "openBluetoothSettings" -> {
                        try {
                            // استفاده از روش دقیق برای باز کردن تنظیمات بلوتوث
                            val intent = Intent().apply {
                                setClassName("com.android.settings", "com.android.settings.bluetooth.BluetoothSettings")
                                flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            }
                            startActivity(intent)
                            result.success(true)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", "تنظیمات بلوتوث باز نشد", null)
                        }
                    }

                    // ── WiFi settings page ────────────────────────────────
                    "openWifiSettings" -> {
                        try {
                            startActivity(
                                Intent(Settings.ACTION_WIFI_SETTINGS)
                                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            )
                            result.success(null)
                        } catch (e: Exception) {
                            result.error("UNAVAILABLE", e.message, null)
                        }
                    }

                    // ── WiFi scan list ────────────────────────────────────
                    "getWifiList" -> {
                        try {
                            val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
                            if (!wm.isWifiEnabled) {
                                result.success(emptyList<Any>())
                                return@setMethodCallHandler
                            }
                            @Suppress("DEPRECATION")
                            wm.startScan()
                            @Suppress("DEPRECATION")
                            val list = wm.scanResults
                                .filter { it.SSID.isNotEmpty() }
                                .distinctBy { it.SSID }
                                .sortedByDescending { it.level }
                                .take(25)
                                .map {
                                    mapOf(
                                        "ssid" to it.SSID,
                                        "level" to it.level,
                                        "secured" to (it.capabilities.contains("WPA")
                                                || it.capabilities.contains("WEP"))
                                    )
                                }
                            result.success(list)
                        } catch (e: Exception) {
                            result.error("ERROR", e.message, null)
                        }
                    }

                    // ── WiFi connect ──────────────────────────────────────
                    "connectToWifi" -> {
                        try {
                            val ssid = call.argument<String>("ssid") ?: ""
                            val password = call.argument<String>("password") ?: ""
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
                                val builder = WifiNetworkSuggestion.Builder().setSsid(ssid)
                                if (password.isNotEmpty()) builder.setWpa2Passphrase(password)
                                wm.removeNetworkSuggestions(wm.networkSuggestions)
                                val status = wm.addNetworkSuggestions(listOf(builder.build()))
                                result.success(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS)
                            } else {
                                @Suppress("DEPRECATION")
                                val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
                                @Suppress("DEPRECATION")
                                val conf = android.net.wifi.WifiConfiguration().apply {
                                    SSID = "\"$ssid\""
                                    if (password.isNotEmpty()) preSharedKey = "\"$password\""
                                    else allowedKeyManagement.set(
                                        android.net.wifi.WifiConfiguration.KeyMgmt.NONE
                                    )
                                }
                                @Suppress("DEPRECATION")
                                val netId = wm.addNetwork(conf)
                                @Suppress("DEPRECATION")
                                wm.disconnect()
                                @Suppress("DEPRECATION")
                                wm.enableNetwork(netId, true)
                                @Suppress("DEPRECATION")
                                wm.reconnect()
                                result.success(true)
                            }
                        } catch (e: Exception) {
                            result.error("ERROR", e.message, null)
                        }
                    }

                    else -> result.notImplemented()
                }
            }
    }
    private fun setMobileDataState(enabled: Boolean) {
        try {
            val connectivityManagerClass = Class.forName(connectivityManager.javaClass.name)
            val method = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean::class.javaPrimitiveType)
            method.isAccessible = true
            method.invoke(connectivityManager, enabled)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun isMobileDataEnabled(): Boolean {
        return try {
            val connectivityManagerClass = Class.forName(connectivityManager.javaClass.name)
            val method = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled")
            method.isAccessible = true
            method.invoke(connectivityManager) as Boolean
        } catch (e: Exception) {
            false
        }
    }
}
