package com.lanyun.wanglaotou.viewModel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import com.lanyun.common.base.BaseViewModel
import com.lanyun.net.ext.*
import com.lanyun.wanglaotou.AppConfig
import com.lanyun.wanglaotou.dao.ERoutingMode
import com.lanyun.wanglaotou.public.PageState
import com.lanyun.wanglaotou.repo.GuestRepo
import com.lanyun.wanglaotou.util.MmkvManager
import com.tencent.mmkv.MMKV

class SettingsViewModel() : BaseViewModel() {

    var viewStates by mutableStateOf(SettingsState())
        private set

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

    override fun onCleared() {
        Log.i(AppConfig.ANG_PACKAGE, "Settings ViewModel is cleared")
        super.onCleared()
    }

    fun dispatch(action: SettingsAction) {
        when (action) {
            is SettingsAction.FetchData -> getGuest(action.url)
        }
    }

    private fun getGuest(url: String) = serverAwait{
        showLoading()
        viewStates = viewStates.copy(pageState = PageState.LoadingDialog)
        GuestRepo.getGuestRedirect(url).serverData().onSuccess {
            onBizError { code, error_message ->
                viewStates = viewStates.copy(pageState = PageState.Error(error_message ?: ""))
            }
            onBizOK<String> { code, data, error_message ->

                data?.let {
                    viewStates = viewStates.copy(
                        url = it,
                        pageState = PageState.Success(it.isEmpty())
                    )
                }

            }
        }.onFailure {
            hidLoading()
            viewStates = viewStates.copy(pageState = PageState.Error(it.message ?: ""))
        }
    }

    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 false
        }
        return true
    }

    fun getDecodeBool(key: String?) : Boolean {

        return settingsStorage?.decodeBool(key,false) ?: false
    }

    fun getDecodeString(key: String?) : String {

        return settingsStorage?.decodeString(key,"") ?: ""
    }



    fun onAppConfigChanged(key: String?,value: Any?) {
        MmkvManager.onAppConfigChanged(key,value)
    }


    fun  decodeAppProxySet() : Boolean{
        val ddd = settingsStorage?.decodeStringSet(AppConfig.PREF_PER_APP_PROXY_SET)
        if (ddd != null){
            return true
        }
        return false
    }
}


data class SettingsState(
    val url: String = "",
    val pageState: PageState = PageState.Loading,
)
sealed class SettingsAction() {
    data class FetchData(val url: String) : SettingsAction()
}