package com.sambath.kunkhmer.screen.fighter

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.sambath.kunkhmer.app.getErrorCode
import com.sambath.kunkhmer.base.BaseViewModel
import com.sambath.kunkhmer.remote.CreateMatchRequest
import com.sambath.kunkhmer.remote.CreateNewsRequest
import com.sambath.kunkhmer.remote.FightersInfo
import com.sambath.kunkhmer.remote.MatchesData
import com.sambath.kunkhmer.remote.service.ApiService
import com.sambath.kunkhmer.util.PrefHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import java.io.File
import java.util.concurrent.TimeUnit

class FighterViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel() {
    private val _state = MutableLiveData<FighterViewState>(FighterViewState())
    val state: LiveData<FighterViewState> = _state
    private fun prev() = _state.value!!

    fun getMatches() {
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)

        disposables.add(
            apiService.getMatches()
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == 1) {
                        _state.value = prev().copy(isProgress = false, isLoginSuccess = true, matchesData = it.data!!)
                    } else {
                        _state.value =
                            prev().copy(isProgress = false, error = "[${it.message.description}]")
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                    _state.value = prev().copy(isProgress = false, error = message)
                })
        )
    }

    fun createMatch(date: String, title: String, desc: String, fighterId: List<String>) {
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)
        val request = CreateMatchRequest(date, title, desc, fighterId)

        disposables.add(
            apiService.createMatch(request)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == 1) {
                        _state.value = prev().copy(isProgress = false, isCreatedMatch = true)
                    } else {
                        _state.value =
                            prev().copy(isProgress = false, error = "[${it.message.description}]")
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                    _state.value = prev().copy(isProgress = false, error = message)
                })
        )
    }

    fun getFighters() {
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)

        disposables.add(
            apiService.getFighters()
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == 1) {
                        _state.value = prev().copy(isProgress = false, isGetFighters = true, fightersData = it.data!!.obj)
                    } else {
                        _state.value =
                            prev().copy(isProgress = false, error = "[${it.message.description}]")
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                    _state.value = prev().copy(isProgress = false, error = message)
                })
        )
    }

    fun createFighter(name: String, desc: String, weight: String, height: String, nationality: String, upload: String) {
        if (_state.value!!.isProgress) return

        val namePart = name.toRequestBody("text/plain".toMediaTypeOrNull())
        val descPart = desc.toRequestBody("text/plain".toMediaTypeOrNull())
        val weightPart = weight.toRequestBody("text/plain".toMediaTypeOrNull())
        val heightPart = height.toRequestBody("text/plain".toMediaTypeOrNull())
        val nationalityPart = nationality.toRequestBody("text/plain".toMediaTypeOrNull())

        if (!upload.isNullOrEmpty()) {
            val file = File(upload)
            val filePart = MultipartBody.Part.createFormData("upload", file.name, file.asRequestBody("image/jpg".toMediaTypeOrNull()))
            _state.value = prev().copy(isProgress = true)

            disposables.add(
                apiService.createFighter(namePart, descPart, weightPart, heightPart, nationalityPart, filePart)
                    .timeout(60, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Log.d("login", it.toString())
                        if (it.resultCode == 1) {
                            _state.value = prev().copy(isProgress = false, isLoginSuccess = true)
                        } else {
                            _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
                        }
                    }, {
                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                        _state.value = prev().copy(isProgress = false, error = message)
                    })
            )
        } else {
            disposables.add(
                apiService.createFighter(namePart, descPart, weightPart, heightPart, nationalityPart)
                    .timeout(60, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Log.d("login", it.toString())
                        if (it.resultCode == 1) {
                            _state.value = prev().copy(isProgress = false, isLoginSuccess = true)
                        } else {
                            _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
                        }
                    }, {
                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                        _state.value = prev().copy(isProgress = false, error = message)
                    })
            )
        }
    }
}

data class FighterViewState(
    val initial: Boolean = false,
    val isProgress: Boolean = false,
    val isLoginSuccess: Boolean = false,
    val isCreatedMatch: Boolean = false,
    val isGetFighters: Boolean = false,
    val error: String? = null,
    val matchesData: MatchesData? = null,
    val fightersData: List<FightersInfo>? = null
)