package com.gamedog.vididin.features.zero

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.DeviceUtil
import com.ama.core.architecture.util.SpUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VidiConst.ZERO_GET_PURCHASE_LIST
import com.gamedog.vididin.VidiConst.ZERO_JOIN_PURCHASE
import com.gamedog.vididin.beans.ZeroBuyItem
import com.gamedog.vididin.beans.ZeroBuyResp
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.netbase.NetworkUtil
import com.gamedog.vididin.netbase.Result
import com.gamedog.vididin.request.RequestUtil
import com.viddin.videos.free.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ZeroBuyViewModel : ViewModel() {
    private val _ZeroBuyListData = MutableStateFlow<Result<ZeroBuyResp>>(Result.Loading)
    val ZeroBuyListData: StateFlow<Result<ZeroBuyResp>> = _ZeroBuyListData.asStateFlow()

    private val _ZeroBuyJoinResult = MutableStateFlow<Result<ZeroBuyItem?>>(Result.Loading)
    val ZeroBuyJoinResult: StateFlow<Result<ZeroBuyItem?>> = _ZeroBuyJoinResult.asStateFlow()


    fun requestJoinZeroBuy(itemId: Int) {
        viewModelScope.launch {
            _ZeroBuyJoinResult.value = Result.Loading

            val operationVal = ZERO_JOIN_PURCHASE
            val curTimeSec = System.currentTimeMillis()/1000
            val signStr = RequestUtil.getZeroBuyRequestSign(curTimeSec, operationVal)
            val requestHeaders = mapOf("Operation" to operationVal.toString(), "Timestamp" to curTimeSec.toString(), "Sign" to signStr)
            val requestParams: MutableMap<String, String> = mutableMapOf("AppId" to AndroidUtil.getPackageId(), "DeviceId" to DeviceUtil.generateDeviceId())
            val userId = AccountManager.getAccount()?.userId?: 0
            if (userId > 0) {
                requestParams.put("UserId", userId.toString())
            }
            val joinZeroBuyItemIds = SpUtil.instance().getList<Int>(SpUtil.KEY_ZEROBUY_JOINED_ACTIVITY_IDS)
            requestParams.put("ActivityId", itemId.toString())


            val result = NetworkUtil.post("${VidiConst.URL_ZERO_BUY}/any", requestHeaders, requestParams, joinZeroBuyItemIds)
            when (result) {
                is Result.Success -> {
                    val respObj = AndroidUtil.json2Object<ZeroBuyResp>(result.data.string())


                    respObj?.contentObj?.let {
                        val itemId = respObj.contentObj?.id
                        if ((respObj.code == 0 || respObj.code == 10003) && itemId != null && itemId > 0) {
                            val mutableJoinedIdList = if(joinZeroBuyItemIds == null) mutableListOf<Int>() else joinZeroBuyItemIds.toMutableList()
                            mutableJoinedIdList.add(itemId)
                            SpUtil.instance().putList(SpUtil.KEY_ZEROBUY_JOINED_ACTIVITY_IDS, mutableJoinedIdList)

                            _ZeroBuyJoinResult.value = Result.Success(respObj?.contentObj)
                            return@launch
                        }
                    }

                    _ZeroBuyJoinResult.value = Result.Error(Throwable("empty response"))
                }
                is Result.Error -> {
                    _ZeroBuyJoinResult.value = Result.Error(result.exception, result.message)
                }
                else -> { }
            }
        }
    }

    fun requestZeroBuyInfo() {
        viewModelScope.launch {
            _ZeroBuyListData.value = Result.Loading

            val operationVal = ZERO_GET_PURCHASE_LIST
            val curTimeSec = System.currentTimeMillis()/1000
            val signStr = RequestUtil.getZeroBuyRequestSign(curTimeSec, operationVal)
            val requestHeaders = mapOf("Operation" to operationVal.toString(), "Timestamp" to curTimeSec.toString(), "Sign" to signStr)
            val requestParams: MutableMap<String, String> = mutableMapOf("AppId" to AndroidUtil.getPackageId(), "DeviceId" to DeviceUtil.generateDeviceId())
            val userId = AccountManager.getAccount()?.userId?: 0
            if (userId > 0) {
                requestParams.put("UserId", userId.toString())
            }
            val joinZeroBuyItemIds = SpUtil.instance().getList<Int>(SpUtil.KEY_ZEROBUY_JOINED_ACTIVITY_IDS)
            val result = NetworkUtil.post("${VidiConst.URL_ZERO_BUY}/any", requestHeaders, requestParams, joinZeroBuyItemIds)
            when (result) {
                is Result.Success -> {
                    val respObj = AndroidUtil.json2Object<ZeroBuyResp>(result.data.string())

                    respObj?.user_id?.let {
                        if (userId <= 0) {
                            AccountManager.saveUserIdInfo(it)
                        }
                    }

                    _ZeroBuyListData.value = Result.Success(respObj!!)
                }
                is Result.Error -> {
                    _ZeroBuyListData.value = Result.Error(result.exception, result.message)
                    AndroidUtil.showToast(R.string.net_error)
                }
                else -> { }
            }
        }
    }


}