package com.adealink.weparty.playmate.saywelcome.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.ExtMutableLiveData
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.App
import com.adealink.weparty.commonui.ext.isFailure
import com.adealink.weparty.commonui.ext.isSuccess
import com.adealink.weparty.module.playmate.data.PLAYMATE_WELCOME_TEXT
import com.adealink.weparty.module.playmate.data.PLAYMATE_WELCOME_VOICE
import com.adealink.weparty.module.playmate.data.SayWelcomeData
import com.adealink.weparty.module.profile.data.VoiceData
import com.adealink.weparty.module.widget.form.field.voice.VoiceWidgetView
import com.adealink.weparty.playmate.data.AddWelcomeReq
import com.adealink.weparty.playmate.data.DeleteWelcomeReq
import com.adealink.weparty.playmate.data.UpdateWelcomeReq
import com.adealink.weparty.playmate.datasource.remote.PlaymateHttpService
import com.adealink.weparty.playmate.saywelcome.data.SayWelcomeItemData
import com.adealink.weparty.playmate.saywelcome.data.onWelcomeAddLD
import com.adealink.weparty.playmate.saywelcome.data.onWelcomeDeleteLD
import com.adealink.weparty.playmate.saywelcome.data.onWelcomeUpdateLD
import kotlinx.coroutines.launch

class WelcomeViewModel : BaseViewModel() {

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

    private val welcomeItemList = mutableListOf<SayWelcomeItemData>()
    val welcomeListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val welcomeListLD = MutableLiveData<List<SayWelcomeItemData>>()

    fun loadWelcomeInfo(): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val rlt = playmateHttpService.getWelcomeList()
            when (rlt) {
                is Rlt.Failed -> {
                    welcomeItemList.clear()
                    welcomeListLD.send(emptyList())
                }

                is Rlt.Success -> {
                    welcomeItemList.clear()
                    welcomeItemList.addAll(
                        rlt.data.data?.list?.map {
                            SayWelcomeItemData(it)
                        } ?: emptyList()
                    )
                    welcomeListLD.send(welcomeItemList)
                }
            }
            liveData.send(rlt)
            welcomeListRltLD.send(rlt)
        }
        return liveData
    }

    fun addWelcome(
        text: String? = null,
        voiceData: VoiceData? = null
    ): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            if (!text.isNullOrEmpty()) {
                liveData.send(
                    addTextWelcome(text)
                )
                return@launch
            }
            if (voiceData != null && !voiceData.isNull()) {
                liveData.send(
                    addVoiceWelcome(voiceData)
                )
                return@launch
            }
        }
        return liveData
    }

    private suspend fun addTextWelcome(text: String): Rlt<Any> {
        val rlt = playmateHttpService.addWelcome(
            AddWelcomeReq(
                type = PLAYMATE_WELCOME_TEXT,
                text = text
            )
        )
        if (rlt.isSuccess) {
            onWelcomeAddLD.send(Unit)
        }
        return rlt
    }

    fun addVoiceWelcome(
        voiceView: VoiceWidgetView
    ): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val uploadRlt = voiceView.beforeSubmit()
            if (uploadRlt.isFailure) {
                liveData.send(uploadRlt)
                return@launch
            }
            val voiceData = voiceView.getVoiceData()
            if (voiceData == null || voiceData.isNull()) {
                liveData.send(Rlt.Failed(CommonDataNullError()))
                return@launch
            }
            liveData.send(
                addVoiceWelcome(voiceData)
            )
        }
        return liveData
    }

    private suspend fun addVoiceWelcome(voice: VoiceData): Rlt<Any> {
        val rlt = playmateHttpService.addWelcome(
            AddWelcomeReq(
                type = PLAYMATE_WELCOME_VOICE,
                voice = voice.url,
                duration = ((voice.duration ?: 0L) / 1000).toInt()
            )
        )
        if (rlt.isSuccess) {
            onWelcomeAddLD.send(Unit)
        }
        return rlt
    }

    fun delete(welcomeId: String): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val rlt = playmateHttpService.deleteWelcome(
                DeleteWelcomeReq(welcomeId)
            )
            if (rlt.isSuccess) {
                onWelcomeDeleteLD.send(welcomeId)
            }
            liveData.send(rlt)
        }
        return liveData
    }

    fun onWelcomeDelete(id: String) {
        viewModelScope.launch {
            welcomeItemList.indexOfFirst { it.data.id == id }.let { pos ->
                if (pos >= 0) {
                    welcomeItemList.removeAt(pos)
                    welcomeListLD.send(welcomeItemList)
                }
            }
        }
    }

    fun updateText(data: SayWelcomeData): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val rlt = playmateHttpService.updateWelcome(
                UpdateWelcomeReq(
                    id = data.id,
                    type = data.type,
                    text = data.text,
                    voice = data.voice,
                    duration = data.voiceDuration
                )
            )
            if (rlt.isSuccess) {
                onWelcomeUpdateLD.send(data.id)
            }
            liveData.send(rlt)
        }
        return liveData
    }

    fun updateVoice(oldData: SayWelcomeData, voiceView: VoiceWidgetView): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            if (oldData.voice == voiceView.getVoiceData()?.url) {
                liveData.send(Rlt.Success(Unit))
                return@launch
            }

            val uploadRlt = voiceView.beforeSubmit()
            if (uploadRlt.isFailure) {
                liveData.send(uploadRlt)
                return@launch
            }
            val voiceData = voiceView.getVoiceData()
            if (voiceData == null || voiceData.isNull()) {
                liveData.send(Rlt.Failed(CommonDataNullError()))
                return@launch
            }

            val rlt = playmateHttpService.updateWelcome(
                UpdateWelcomeReq(
                    id = oldData.id,
                    type = oldData.type,
                    voice = voiceData.url,
                    duration = ((voiceData.duration ?: 0L) / 1000).toInt()
                )
            )
            if (rlt.isSuccess) {
                onWelcomeUpdateLD.send(oldData.id)
            }
            liveData.send(rlt)
        }
        return liveData
    }

}