package com.remax.visualnovel.manager.gift

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.remax.visualnovel.api.factory.ServiceFactory
import com.remax.visualnovel.entity.request.Gift
import com.remax.visualnovel.repository.api.DictRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by HJW on 2025/9/17
 */
object GiftManager : DefaultLifecycleObserver {

    var gifts: List<Gift>? = null
        private set(value) {
            value?.firstOrNull()?.select = true
            field = value
        }

    private val dictRepository by lazy {
        DictRepository(ServiceFactory.createService())
    }

    fun initSelect(){
        gifts?.forEachIndexed { index, gift ->
            gift.select = index == 0
        }
    }

    fun getGift() {
        CoroutineScope(Dispatchers.IO).launch {
            dictRepository.getGiftDict().transformResult({
                gifts = it?.datas
            })
        }
    }

    override fun onResume(owner: LifecycleOwner) {
        if (gifts == null) {
            getGift()
        }
    }
}