package com.adealink.weparty.playmate.list.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.CommonDataNullError
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.App
import com.adealink.weparty.module.room.data.RoomInfo
import com.adealink.weparty.playmate.datasource.remote.PlaymateHttpService
import kotlinx.coroutines.launch

class PlaymateRoomViewModel : BaseViewModel() {

    private val playmateHttpService by lazy {
        App.instance.networkService.getHttpService(PlaymateHttpService::class.java)
    }


    val roomAvailableLD = MutableLiveData<Boolean>()

    private var lastCheckRoomAvailableTs = 0L
    private var isChecking = false
    fun checkRoomAvailable() {
        viewModelScope.launch {
            if (isChecking || System.currentTimeMillis() - lastCheckRoomAvailableTs < 60_000) {
                return@launch
            }
            isChecking = true
            val rlt = playmateHttpService.isRoomAvailable()
            isChecking = false
            lastCheckRoomAvailableTs = System.currentTimeMillis()
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success -> {
                    roomAvailableLD.send(rlt.data.data?.available ?: false)
                }
            }
        }
    }

    fun getAvailableRoomId(): LiveData<Rlt<RoomInfo>> {
        val liveData = OnceMutableLiveData<Rlt<RoomInfo>>()
        viewModelScope.launch {
            val rlt = playmateHttpService.getAvailableRoom()
            when (rlt) {
                is Rlt.Failed -> {
                    liveData.send(rlt)
                    return@launch
                }

                is Rlt.Success -> {
                    val roomInfo = rlt.data.data?.room
                    if (roomInfo == null) {
                        liveData.send(Rlt.Failed(CommonDataNullError()))
                        return@launch
                    }
                    liveData.send(Rlt.Success(roomInfo))
                    return@launch
                }
            }
        }
        return liveData
    }

}