package com.lanyun.wanglaotou.viewModel

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue

import androidx.lifecycle.MutableLiveData
import com.lanyun.common.base.BaseViewModel
import com.lanyun.common.baseDate.updateMainEvent
import com.lanyun.common.model.MainEvent
import com.lanyun.wanglaotou.App
import com.lanyun.wanglaotou.AppConfig
import com.lanyun.wanglaotou.dao.ERoutingMode
import com.lanyun.wanglaotou.model.NodeModel
import com.lanyun.wanglaotou.model.UserSubModel
import com.lanyun.wanglaotou.util.AngConfigManager
import com.lanyun.wanglaotou.util.MessageUtil
import com.lanyun.wanglaotou.util.MmkvManager
import com.lanyun.wanglaotou.util.VPNManager
import com.tencent.mmkv.MMKV

class MainViewModel: BaseViewModel() {
    private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }

    var viewStates by mutableStateOf(MainViewState())
        private set

    val isRunning by lazy { MutableLiveData<Boolean>() }

    val menuItemSelected by lazy { MutableLiveData<Int>() }

    val toBuyUrl by  lazy { MutableLiveData<String>() }


    fun startListenBroadcast(context: Context) {
        isRunning.value = false
        context.registerReceiver(mMsgReceiver, IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY))
        MessageUtil.sendMsg2Service(context, AppConfig.MSG_REGISTER_CLIENT, "")
    }
    private fun updateListAction(n: Int) {
        viewStates = viewStates.copy(updateListAction= n)
    }

    fun updateExpanded(n: Boolean) {
        viewStates = viewStates.copy(expanded= n)
    }

    fun updateVpnState(n:VpnState){
        viewStates = viewStates.copy(vpnState= n)
    }

    fun testCurrentServerRealPing() {
        viewStates = viewStates.copy(updateTestResultAction=  "测试中")
        MessageUtil.sendMsg2Service(App.CONTEXT, AppConfig.MSG_MEASURE_DELAY, "")
    }

    private fun getSelectNode() : NodeModel?{
        return MmkvManager.decodeSelectServer()
    }

    private fun getUserInfo() : UserSubModel?{
        return MmkvManager.decodeSubUserInfo()
    }


    fun getAppRouteMode(key: String?) : Boolean {
        val route_mode = settingsStorage?.decodeString(key,"")
        if (route_mode.isNullOrEmpty()){
            return false
        }
        if (route_mode == ERoutingMode.BYPASS_LAN_MAINLAND.value){
            return true
        }
        return false
    }

    fun initGlobalData(){
        settingsStorage?.encode(AppConfig.PREF_MODE,"VPN")
        val routingMode = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_MODE) ?: ERoutingMode.GLOBAL_PROXY.value
        settingsStorage?.encode(AppConfig.PREF_ROUTING_MODE,routingMode)
        settingsStorage?.encode(AppConfig.PREF_LOCAL_DNS_ENABLED,true)
        settingsStorage?.encode(AppConfig.PREF_FAKE_DNS_ENABLED,false)
        settingsStorage?.encode(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY,"IPIfNonMatch")
        settingsStorage?.encode(AppConfig.PREF_SPEED_ENABLED,true)
        settingsStorage?.encode(AppConfig.PREF_SNIFFING_ENABLED,true)
        settingsStorage?.encode(AppConfig.PREF_LOGLEVEL,"warning")

    }

    fun startVpn(){

        val userSubModel = getUserInfo()
        val nodeModel = getSelectNode()

        if (nodeModel!=null && userSubModel!=null){
            //AngConfigManager.importConfig(nodeModel,userSubModel.uuid,null)

           // updteconfig(nodeModel,userSubModel)
            if (isRunning.value == false){
//                isRunning.value = true
                updateVpnState(VpnState.MainConnecting)
                viewStates = viewStates.copy(updateTestResultAction=  "连接中...")
                VPNManager.get().startVpn()
            } else {
                VPNManager.get().stopVpn()
            }
        } else {
            updateVpnState(VpnState.Error("没有选中节点"))
        }
    }

    fun road(){
        if (isRunning.value == true){
            VPNManager.get().road()
        }

    }




    private val mMsgReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctx: Context?, intent: Intent?) {
            when (intent?.getIntExtra("key", 0)) {
                AppConfig.MSG_STATE_RUNNING -> {
                    isRunning.value = true
                    //updateVpnState(VpnState.MainConnecting)
                    viewStates = viewStates.copy(updateTestResultAction=  "开始连接",isRunning=isRunning.value ?: false)
                }
                AppConfig.MSG_STATE_NOT_RUNNING -> {
                    isRunning.value = false
                   // updateVpnState(VpnState.MainIdLe)
                    viewStates = viewStates.copy(updateTestResultAction=  "未连接",isRunning=isRunning.value ?: false,vpnState = VpnState.MainIdLe)
                }
                AppConfig.MSG_STATE_START_SUCCESS -> {
                    isRunning.value = true
                   // updateVpnState(VpnState.MainConnected)
                    viewStates = viewStates.copy(updateTestResultAction=  "连接完成,点击测试",isRunning=isRunning.value ?: false,vpnState = VpnState.MainConnected)
                }
                AppConfig.MSG_STATE_START_FAILURE -> {
                   // getApplication<AngApplication>().toast(R.string.toast_services_failure)
                    isRunning.value = false
                 //   updateVpnState(VpnState.Error("连接失败"))
                    viewStates = viewStates.copy(updateTestResultAction=  "连接失败",isRunning=isRunning.value ?: false,vpnState = VpnState.Error("连接失败"))
                }
                AppConfig.MSG_STATE_STOP_SUCCESS -> {
                    isRunning.value = false
                  //  updateVpnState(VpnState.MainStop)
                    viewStates = viewStates.copy(updateTestResultAction=  "未连接",isRunning=isRunning.value ?: false,vpnState = VpnState.MainStop)
                }
                AppConfig.MSG_MEASURE_DELAY ->{
                    viewStates = viewStates.copy(updateTestResultAction=  "测试中",isRunning=isRunning.value ?: false)
                }
                AppConfig.MSG_MEASURE_DELAY_SUCCESS -> {
                    val content = intent.getStringExtra("content")
                    viewStates = viewStates.copy(updateTestResultAction=  content ?: "",isRunning=isRunning.value ?: false)

                }
                AppConfig.MSG_MEASURE_CONFIG_SUCCESS -> {
                    val resultPair = intent.getSerializableExtra("content") as Pair<String, Long>
                    MmkvManager.encodeServerTestDelayMillis(resultPair.first, resultPair.second)
                    updateMainEvent(MainEvent.MainLegacy)
                   viewStates = viewStates.copy(isRunning=isRunning.value ?: false)
//                    updateListAction.value = getPosition(resultPair.first)
                    //viewStates = viewStates.copy(updateListAction=  getPosition(resultPair.first))
                }
            }
        }
    }

}

//MainConnecting,
//MainConnected,
//MainStop,//CONNECTED
//MainIdLe,
//MainStopping  //STOPPING
sealed class VpnState {
    object MainConnecting : VpnState()
    object MainConnected : VpnState()
    object MainStop : VpnState()
    object MainIdLe : VpnState()
    object MainStopping : VpnState()
    data class Error(val exception: String) : VpnState()
}

data class MainViewState(
    var updateListAction:Int = -1,
    var expanded : Boolean = false,
    var updateTestResultAction: String = "未连接",
    var isRunning : Boolean = false,
    var vpnState: VpnState = VpnState.MainStop
){

}