package app.xixi.nomo

import CoreApi
import FlutterError
import OnEventChangeStreamHandler
import PigeonEventSink
import android.app.Activity
import android.content.Context.TELEPHONY_SERVICE
import android.content.Intent
import android.net.VpnService
import android.telephony.TelephonyManager
import android.util.Log
import com.google.gson.Gson
import io.flutter.plugin.common.BinaryMessenger
import java.io.InputStream
import java.util.UUID

class CoreApiImpl(private val activity: Activity) : CoreApi {
    companion object {
        private const val TAG = "CoreApiImpl"
        private const val REQUEST_VPN_PERMISSION = 1001
    }
    
    // 事件流处理器
    private var eventSink: PigeonEventSink<String>? = null

    // xray服务
    private var xrayApi: XRayApi? = null
    
    // 事件流处理器实现
    private val eventStreamHandler = object : OnEventChangeStreamHandler() {
        override fun onListen(p0: Any?, sink: PigeonEventSink<String>) {
            Log.d(TAG, "Flutter 开始监听事件变化")
            eventSink = sink
        }
        
        override fun onCancel(p0: Any?) {
            Log.d(TAG, "Flutter 取消监听事件变化")
            eventSink = null
        }
    }
    
    // 注册事件流处理器
    fun registerEventStreamHandler(messenger: BinaryMessenger) {
        OnEventChangeStreamHandler.register(messenger, eventStreamHandler)
        Log.d(TAG, "事件流处理器已注册")
    }

    // 通知 Flutter 连接状态变化
    private fun notifyConnectionStateChange(state: String) {
        eventSink?.let { sink ->
            try {
                sink.success(state)
                Log.d(TAG, "已通知 Flutter 连接状态变化: $state")
            } catch (e: Exception) {
                Log.e(TAG, "通知 Flutter 失败", e)
            }
        } ?: Log.w(TAG, "事件流未连接，无法通知 Flutter")
    }

    /**
     * 初始化xray服务
     */
    fun initXrayApi() {
        VLog.i(TAG, "CoreApiImpl.initXrayApi() 创建 XRayApi 实例")
        xrayApi = XRayApi()
    }

    /**
     * 设置XRayApi状态监听
     */
    fun setXRayApiStatusListener() {
        xrayApi?.setVpnStatusEventListener { status, message ->
            VLog.i(TAG, "接收到VPN状态变化: status=$status, message=$message")
            // 根据状态码转换连接状态
            val connectionState = when (status) {
                0L -> "disconnected"
                1L -> "connecting"
                2L -> "connected"
                3L -> "error"
                else -> "unknown"
            }
            // 通知Flutter连接状态变化
            notifyConnectionStateChange(connectionState)
        }
    }

    fun xrayInit() {
        VLog.i(TAG, "CoreApiImpl.xrayInit() 被调用")
        xrayApi?.init(activity)
        VLog.i(TAG, "CoreApiImpl.xrayInit() 调用完成")
    }

    fun xrayUnInit() {
        xrayApi?.uninit()
    }


    override fun getApps(): String? {
        TODO("Not yet implemented")
    }

    override fun getSystemLocale(): String? {
        TODO("Not yet implemented")
    }

    override fun connect(): Boolean? {
        Log.i(TAG, "Starting V2Ray with permission check")
        // 检查VPN权限
        val intent = VpnService.prepare(activity)
        if (intent == null) {
            // 已有VPN权限，直接启动
            Log.i(TAG, "VPN permission already granted")
            startV2RayService()
        } else {
            // 需要请求VPN权限
            Log.i(TAG, "Requesting VPN permission")
            activity.startActivityForResult(intent, REQUEST_VPN_PERMISSION)
        }
        return true
    }

    override fun disconnect(): Boolean? {
        VLog.i(TAG, "============ 开始停止 V2Ray 服务 ============")
        
        // 通知 Flutter 开始断开连接
        notifyConnectionStateChange("disconnecting")

        // 停止V2Ray服务
        VLog.i(TAG, "调用 xrayApi.stopXray()")
        xrayApi?.stopXray()
        xrayUnInit()
        VLog.i(TAG, "V2Ray 服务停止完成")
        notifyConnectionStateChange("disconnected")
        return true
    }

    override fun getRemoteIp(): String? {
        TODO("Not yet implemented")
    }

    override fun getAdvertisingId(): String? {
        TODO("Not yet implemented")
    }

    override fun moveTaskToBack(): Boolean? {
        try {
            activity.moveTaskToBack(true)
            return true
        } catch (e: Exception) {
            throw FlutterError("-1", e.message)
        }
    }

    override fun isConnected(): Boolean? {
        val isRunning = XRayApi.isServiceRunning(activity)
        VLog.i(TAG, "XRayService is running = $isRunning")
        return isRunning
    }

    override fun getSimInfo(): String? {
        try {
            val telephonyManager = activity.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
            val simState = telephonyManager.simState
            val simReady = simState == TelephonyManager.SIM_STATE_READY

            val carrierName = telephonyManager.simOperatorName ?: "Unknown"
            val simOperator = telephonyManager.simOperator ?: ""
            val simCountryIso = telephonyManager.simCountryIso ?: ""
            val mcc = if (simOperator.length >= 3) simOperator.substring(0, 3) else ""
            val mnc = if (simOperator.length > 3) simOperator.substring(3) else ""

            val networkCarrierName = telephonyManager.networkOperatorName ?: "Unknown"
            val networkOperator = telephonyManager.networkOperator ?: ""
            val networkCountryIso = telephonyManager.networkCountryIso ?: ""
            val networkMcc =
                if (networkOperator.length >= 3) networkOperator.substring(0, 3) else ""
            val networkMnc = if (networkOperator.length > 3) networkOperator.substring(3) else ""

            val data = mapOf(
                "simReady" to simReady,
                "carrierName" to carrierName,
                "mcc" to mcc,
                "mnc" to mnc,
                "countryIso" to simCountryIso,
                "networkCarrierName" to networkCarrierName,
                "networkMcc" to networkMcc,
                "networkMnc" to networkMnc,
                "networkCountryIso" to networkCountryIso
            )
            return Gson().toJson(data)
        } catch (e: Exception) {
            throw FlutterError("-1", e.message)
        }
    }

    override fun reconnect(): Boolean? {
        xrayInit()
        return true
    }

    fun startV2RayService() {
        VLog.i(TAG, "============ 开始启动 V2Ray 服务 ============")

        // 通知 Flutter 开始连接
        notifyConnectionStateChange("connecting")
        
        // 1. 初始化 XRay (启动和绑定服务)
        VLog.i(TAG, "步骤 1: 调用 xrayInit() 初始化服务")
        xrayInit()
        
        // 2. 启动 XRay (发送启动消息)
        // 注意：startXray() 内部已经处理了等待服务连接的逻辑
        // 如果服务还在连接中 (XRAY_SVR_CONNECT_SERVICE)，会注册回调等待
        // 如果服务已连接 (XRAY_SVR_SERVICE_WORKING)，会直接发送启动消息
        VLog.i(TAG, "步骤 2: 调用 startXray() 启动代理")
        startXray()
        
        VLog.i(TAG, "startV2RayService 调用完成，等待服务连接和启动")
        // 注意：实际的连接成功应该在服务启动完成后通知
        // 这里先暂时保持原有逻辑
        notifyConnectionStateChange("connected")
    }

    /**
     * 查询统计信息
     */
    fun queryStats() {
        Log.i(TAG, "Querying V2Ray stats...")
    }
    
    /**
     * 通知 Flutter 统计信息更新
     */
    fun notifyStatsUpdate(uplink: Long, downlink: Long) {
        val statsJson = "{\"uplink\":$uplink,\"downlink\":$downlink}"
        notifyConnectionStateChange("stats_update:$statsJson")
    }
    
    /**
     * 通知 Flutter 错误信息
     */
    fun notifyError(errorMessage: String) {
        notifyConnectionStateChange("error:$errorMessage")
    }
    
    /**
     * 通知 Flutter 服务状态变化
     */
    fun notifyServiceStatus(isRunning: Boolean) {
        val status = if (isRunning) "running" else "stopped"
        notifyConnectionStateChange("service_status:$status")
    }

    // 启动V2Ray服务
    private fun startXray() {
        VLog.i(TAG, "CoreApiImpl.startXray() 被调用，开始准备配置")
        
        val config = XrayConfig()
        config.sessionId = UUID.randomUUID().toString()
        config.socksPort = 10808
        
        VLog.i(TAG, "生成的 sessionId: ${config.sessionId}")
        VLog.i(TAG, "socksPort: ${config.socksPort}")
        
        val detectOptions = StatusDetectOptions()
        detectOptions.statusDetectInterval = 60
        val detectUrls = ArrayList<String>()
        detectUrls.add("https://www.baidu.com")
        detectOptions.statusDetectUrls = detectUrls
        
        val proxyNodes= ArrayList<ProxyNode>()
        val proxyNode = ProxyNode()
        proxyNode.nodeId = "10001"
        proxyNode.coreConfig = readAssets("connect.json")
        proxyNodes.add(proxyNode)
        
        VLog.i(TAG, "读取配置文件: connect.json")
        
        val startOptions = ProxyStartOptions()
        startOptions.socksPort = config.socksPort
        startOptions.nodes = proxyNodes
        startOptions.statusDetectOptions = detectOptions
        config.startOptions = startOptions
        
        VLog.i(TAG, "配置准备完成，调用 xrayApi.startXray()")
        val result = xrayApi?.startXray(config)
        VLog.i(TAG, "xrayApi.startXray() 返回结果: $result")
    }


    private fun readAssets(fileName: String): String {
        try {
            val `in`: InputStream = activity.resources.assets.open(fileName)
            val lenght = `in`.available()
            val buffer = ByteArray(lenght)
            `in`.read(buffer)
            return String(buffer, charset("utf-8"))
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return ""
        }
    }

    /**
     * 处理Activity结果（需要在Activity的onActivityResult中调用）
     */
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_VPN_PERMISSION) {
            if (resultCode == Activity.RESULT_OK) {
                Log.i(TAG, "VPN permission granted, starting V2Ray service")
                startV2RayService()
            } else {
                Log.w(TAG, "VPN permission denied")
                notifyConnectionStateChange("permission_denied")
            }
        }
    }
}