package com.adealink.weparty.country.manager

import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.data.json.froJsonErrorNull
import com.adealink.frame.data.json.toJsonErrorNull
import com.adealink.frame.frame.BaseFrame
import com.adealink.weparty.App
import com.adealink.weparty.country.data.CountryData
import com.adealink.weparty.country.datasource.CountryHttpService
import com.adealink.weparty.country.datasource.CountyLocalService
import kotlinx.coroutines.withContext

val countryManager: ICountryManager by fastLazy { CountryManager() }

class CountryManager : BaseFrame<ICountryListener>(), ICountryManager {

    private val countryHttpService by fastLazy {
        App.instance.networkService.getHttpService(CountryHttpService::class.java)
    }

    private var countryList = listOf<CountryData>()
    private var cacheTs = 0L

    override suspend fun pullCountryList(): List<CountryData> {
        if (countryList.isNotEmpty() && (System.currentTimeMillis() - cacheTs < 3_600_000)) {
            return countryList
        }

        if (countryList.isEmpty()) {
            val cacheList = loadFromCache()
            if (cacheList.isNotEmpty()) {
                countryList = cacheList
                cacheTs = System.currentTimeMillis()
                return cacheList
            }
        }

        val rlt = countryHttpService.getSupportMobileCode()
        when (rlt) {
            is Rlt.Failed -> {
                return emptyList()
            }

            is Rlt.Success -> {
                val countryList = rlt.data.data?.list
                    ?: emptyList()
                this.countryList = countryList
                cacheTs = System.currentTimeMillis()
                save(countryList)
                return countryList
            }
        }
    }

    private suspend fun loadFromCache(): List<CountryData> {
        return withContext(Dispatcher.WENEXT_THREAD_POOL) {
            froJsonErrorNull<List<CountryData>>(CountyLocalService.countryList) ?: emptyList()
        }
    }

    private suspend fun save(countryList: List<CountryData>) {
        withContext(Dispatcher.WENEXT_THREAD_POOL) {
            CountyLocalService.countryList = toJsonErrorNull(countryList) ?: ""
        }
    }


}