package com.adealink.weparty.country.viewmodel

import androidx.lifecycle.LiveData
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.country.data.CountryData
import com.adealink.weparty.country.manager.countryManager
import com.adealink.weparty.util.PinyinUtils
import com.adealink.weparty.util.PinyinUtils.containsChinese
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume

class CountryViewModel : BaseViewModel() {

    fun loadCountryList(): LiveData<List<CountryData>> {
        val liveData = OnceMutableLiveData<List<CountryData>>()
        viewModelScope.launch {
            val countryList = countryManager.pullCountryList()
            val sortList = withContext(Dispatcher.WENEXT_THREAD_POOL) {
                sortCountryList(countryList)
            }
            liveData.send(sortList)
        }
        return liveData
    }



    private suspend fun sortCountryList(countryList: List<CountryData>): List<CountryData> {
        return suspendCancellableCoroutine { continuation ->
            for (data in countryList) {
                if (data.name.containsChinese()) {
                    //中文转pinyin
                    data.pinyinName = PinyinUtils.getFullPinyinSafely(data.name)
                }
            }
            if (continuation.isActive) {
                val sortList = countryList.sortedBy { it.getDisplayName() }
                continuation.resume(sortList)
                return@suspendCancellableCoroutine
            }
        }
    }

}