package es.verdnatura.presentation.view.feature.photos.fragment

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import es.verdnatura.domain.SilexCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.ResponseItemVO
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response
import retrofit2.http.Header
import retrofit2.http.Part
import retrofit2.http.QueryMap
import java.io.File
import java.util.*


class PhotosViewModel(val context: Context) : BaseViewModel(context) {


    private val _responseinsert by lazy { MutableLiveData<ResponseItemVO>() }
    val responseinsert: LiveData<ResponseItemVO>
        get() = _responseinsert


    fun uploadPhoto(
        // val img = dataURItoBlob(cropper.getCroppedCanvas().toDataURL("image/png"))
        urlImage:String,
        itemFK:Int = 11 ,
        itemId:String = "11" ,
        date: Date = Date(),
        timestamp: Long = date.time,
        fileName: String = "${itemFK}_$timestamp",
        file: File = File("$urlImage"),
        fileRequestBody: RequestBody = RequestBody.create(MediaType.parse("image/jpeg"), file),
        filePart: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.name, fileRequestBody),
        fileNameRequestBody: RequestBody = RequestBody.create(MediaType.parse("text/plain"), fileName),



    ) {
        salix.uploadImage("catalog",itemFK,filePart)
            .enqueue(object : SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseinsert.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                        _responseinsert.value = ResponseItemVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                }

            })
    }


}