package kr.co.vividnext.sodalive.message.voice

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
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.message.MessageRepository
import kr.co.vividnext.sodalive.message.SendVoiceMessageRequest
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

class VoiceMessageWriteViewModel(private val repository: MessageRepository) : BaseViewModel() {
    var recipientId: Long = 0

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

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

    fun write(file: File, onSuccess: () -> Unit) {
        if (recipientId <= 0) {
            _toastLiveData.postValue("받는 사람을 선택해 주세요.")
            return
        }

        val request = SendVoiceMessageRequest(recipientId)
        val requestJson = Gson().toJson(request)

        val recordedFile = MultipartBody.Part.createFormData(
            "voiceMessageFile",
            file.name,
            file.asRequestBody("audio/mpeg".toMediaType())
        )
        _isLoading.value = true
        compositeDisposable.add(
            repository.sendVoiceMessage(
                recordedFile,
                requestJson.toRequestBody("text/plain".toMediaType()),
                "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false
                        if (it.success) {
                            _toastLiveData.postValue("메시지 전송이 완료되었습니다.")
                            onSuccess()
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }
                    },
                    {
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        _isLoading.postValue(false)
                    }
                )
        )
    }
}
