package com.sambath.kunkhmer.screen.shop

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.CreateNewsRequest
import com.sambath.kunkhmer.remote.CreateProductRequest
import com.sambath.kunkhmer.remote.LivesInfo
import com.sambath.kunkhmer.remote.ProductInfo
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 java.io.File
import java.util.concurrent.TimeUnit

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

    data class ProductViewState(
        val initial: Boolean = false,
        val isProgress: Boolean = false,
        val isLoginSuccess: Boolean = false,
        val error: String? = null,
        val productData: MutableList<ProductInfo>? = null,
    )

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

        disposables.add(
            apiService.getProducts()
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == 1) {
                        _state.value = prev().copy(isProgress = false, isLoginSuccess = true, productData = 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 createProduct(name: String, desc: String, price: String, upload: String) {
        if (_state.value!!.isProgress) return
        //val request = CreateProductRequest(name, desc, price, upload)
        _state.value = prev().copy(isProgress = true)

        val namePart = name.toRequestBody("text/plain".toMediaTypeOrNull())
        val descPart = desc.toRequestBody("text/plain".toMediaTypeOrNull())
        val pricePart = price.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.createProduct(namePart, descPart, pricePart, filePart)
                    .timeout(10, 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() + it.message
                        _state.value = prev().copy(isProgress = false, error = message)
                    })
            )
        } else {
            disposables.add(
                apiService.createProduct(namePart, descPart, pricePart)
                    .timeout(10, 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() + it.message
                        _state.value = prev().copy(isProgress = false, error = message)
                    })
            )
        }
    }
}