package kr.co.vividnext.sodalive.live.room.detail

import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.firebase.dynamiclinks.ShortDynamicLink
import com.google.firebase.dynamiclinks.ktx.androidParameters
import com.google.firebase.dynamiclinks.ktx.dynamicLinks
import com.google.firebase.dynamiclinks.ktx.iosParameters
import com.google.firebase.dynamiclinks.ktx.shortLinkAsync
import com.google.firebase.ktx.Firebase
import com.orhanobut.logger.Logger
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.live.LiveRepository

class LiveRoomDetailViewModel(private val repository: LiveRepository) : BaseViewModel() {
    private val _liveRoomDetailLiveData = MutableLiveData<GetRoomDetailResponse>()
    val liveRoomDetailLiveData: MutableLiveData<GetRoomDetailResponse>
        get() = _liveRoomDetailLiveData

    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

    private var _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean>
        get() = _isLoading

    fun getDetail(roomId: Long, onFailure: () -> Unit) {
        if (!_isLoading.value!!) {
            _isLoading.value = true
        }

        compositeDisposable.add(
            repository.getRoomDetail(roomId, token = "Bearer ${SharedPreferenceManager.token}")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false
                        if (it.success && it.data != null) {
                            _liveRoomDetailLiveData.postValue(it.data!!)
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                            onFailure()
                        }
                    },
                    {
                        _isLoading.value = false
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        onFailure()
                    }
                )
        )
    }

    fun shareRoomLink(
        roomId: Long,
        isPrivateRoom: Boolean,
        password: Int?,
        onSuccess: (String) -> Unit
    ) {
        _isLoading.value = true
        Firebase.dynamicLinks.shortLinkAsync(ShortDynamicLink.Suffix.SHORT) {
            link = Uri.parse("https://sodalive.net/?room_id=$roomId")
            domainUriPrefix = "https://sodalive.page.link"
            androidParameters { }
            iosParameters("kr.co.vividnext.sodalive") {
                appStoreId = "6461721697"
            }
        }.addOnSuccessListener {
            val uri = it.shortLink
            if (uri != null) {
                val message = if (isPrivateRoom) {
                    "${SharedPreferenceManager.nickname}님이 귀하를 " +
                        "보이스온의 비공개라이브에 초대하였습니다.\n" +
                        "※ 라이브 참여: $uri\n" +
                        "(입장 비밀번호 : $password)"
                } else {
                    "${SharedPreferenceManager.nickname}님이 귀하를 " +
                        "보이스온의 공개라이브에 초대하였습니다.\n" +
                        "※ 라이브 참여: $uri"
                }

                onSuccess(message)
            }
        }.addOnFailureListener {
            _toastLiveData.postValue("공유링크를 생성하지 못했습니다.\n다시 시도해 주세요.")
        }.addOnCompleteListener {
            _isLoading.value = false
        }
    }
}
