package com.ccwangluo.accelerator.ui.gameList

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.ccwangluo.accelerator.model.Game
import com.ccwangluo.accelerator.model.GameInfo
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.accelerator.utils.http.HttpGo
import com.github.shadowsocks.bg.BaseService
import com.umeng.socialize.utils.DeviceConfigInternal.context
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xutil.app.AppUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.URLDecoder
import java.net.URLEncoder

class GameListModel : ViewModel() {

    val gameModel = MutableLiveData<Game>()
    val clearList = MutableLiveData<Boolean>()
    val gameList = mutableListOf<String>()

    fun freshData(xPageFragment: XPageFragment, page: Int) {
        var packageName =
            if (AcceleratorUtils.game == null || AcceleratorUtils.state != BaseService.State.Connected) "" else AcceleratorUtils.game!!.packageName

        xPageFragment.lifecycleScope.launch(Dispatchers.IO) {
            if (page == 1 || gameList.size == 0) {
                getSupportGameList(xPageFragment)
            }
            var gamelist = ""
            xPageFragment.context?.let {
                var applist = StringBuffer()
                for (s in SysUtils.getAllAppInfo(it)) {
                    if (gameList.contains(s)){
                        applist.append(s + ",")
                    }
                }
                if (applist.isNotBlank()){
                    gamelist = applist.substring(0,applist.lastIndex -1)
                }
            }
            val res =
                HttpGo.getSync<Game>("/api/new/game/list?page=${page}&status=1&size=10&channelId=${SysUtils.getChannel()}&packageName=${packageName}&packageNameList=${gamelist}")
            res?.let {
                it.data?.let {
                    clearList.postValue(page == 1)
                    gameModel.postValue(it)
                }

            }
        }
    }

    suspend fun getSupportGameList(xPageFragment: XPageFragment) {
            val res =
                HttpGo.getSync<List<String>>("/api/new/game/getPackageNameList?channelId=${SysUtils.getChannel()}")
            res?.let {
                it.data?.let { it1 -> gameList.addAll(it1) }
            }
    }

}