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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import es.verdnatura.domain.SalixCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.common.Event
import es.verdnatura.presentation.view.feature.packaging.model.EntryList
import es.verdnatura.presentation.view.feature.packaging.model.EntrySalix
import es.verdnatura.presentation.view.feature.packaging.model.ItemSupplier
import es.verdnatura.presentation.view.feature.packaging.model.ItemSupplierList
import es.verdnatura.presentation.view.feature.packaging.model.NotificationQueue
import es.verdnatura.presentation.view.feature.packaging.model.ObervationEntry
import es.verdnatura.presentation.view.feature.packaging.model.Supplier
import es.verdnatura.presentation.view.feature.packaging.model.SupplierList
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

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

    private val _itemSupplierList by lazy { MutableLiveData<ItemSupplierList>() }
    val itemSupplierList: LiveData<ItemSupplierList>
        get() = _itemSupplierList

    private val _supplierList by lazy { MutableLiveData<SupplierList>() }
    val supplierList: LiveData<SupplierList>
        get() = _supplierList

    private val _entryList by lazy { MutableLiveData<EntryList>() }
    val entryList: LiveData<EntryList>
        get() = _entryList

    private val _entry by lazy { MutableLiveData<EntrySalix>() }
    val entry: LiveData<EntrySalix>
        get() = _entry

    private val _entryUpdate by lazy { MutableLiveData<Boolean>() }
    val entryUpdate: LiveData<Boolean>
        get() = _entryUpdate

    val loadEntryUpdate: LiveData<Event<Boolean>> = _entryUpdate.map { Event(it) }

    private val _entryAdd by lazy { MutableLiveData<Boolean>() }
    val entryAdd: LiveData<Boolean>
        get() = _entryAdd

    private val _responseNotification by lazy { MutableLiveData<Boolean>() }
    val responseNotification: LiveData<Boolean>
        get() = _responseNotification

    val loadEntryAdd: LiveData<Event<Boolean>> = _entryAdd.map { Event(it) }

    fun getSuppliers() {
        salix.getSuppliers().enqueue(object : SalixCallback<List<Supplier>>(context) {

            override fun onSuccess(response: Response<List<Supplier>>) {
                _supplierList.value = response.body()?.let { SupplierList(it) }

            }

        })
    }

    fun getEntriesFromSupplier(supplier: Int) {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, 0)

        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val today = dateFormat.format(calendar.time)

        salix.getEntriesFromSupplier("""{"where": {"supplierFk": "$supplier","created":{"gte":"$today"},"typeFk":"packaging","order":"created ASC"},"include": [ { "relation": "travel", "scope": { "fields": ["landed"]}}]}""")
            .enqueue(object : SalixCallback<List<EntrySalix>>(context) {

                override fun onSuccess(response: Response<List<EntrySalix>>) {
                    _entryList.value = response.body()?.let { EntryList(it) }
                }

            })
    }

    fun entryUpdateObserv(entryId: Int, observation: String) {
        salix.entryUpdateObserv(entryId, ObervationEntry(observation))
            .enqueue(object : SalixCallback<EntrySalix>(context) {

                override fun onSuccess(response: Response<EntrySalix>) {
                    _entryUpdate.value = true
                }
            })
    }

    fun entryUploadPhotoSalix(
        idEntry: Number,
        warehouseId: Number,
        companyId: Number,
        dmsTypeId: Number,
        reference: String,
        description: String,
        hasFile: Boolean,
        urlImage: String,

        ) {

        val file = File(urlImage)
        val fileRequestBody: RequestBody = RequestBody.create(MediaType.parse("image/jpeg"), file)

        salix.uploadEntryPhoto(
            idEntry,
            warehouseId,
            companyId,
            dmsTypeId,
            reference,
            description,
            hasFile,
            file = MultipartBody.Part.createFormData(
                "file", file.name, fileRequestBody
            )
        ).enqueue(object : SalixCallback<Any>(context) {})
    }

    fun entryAddFromBuy(id: Number, item: Number, printedStickers: Number) {
        salix.addFromBuy(id, item, printedStickers)
            .enqueue(object : SalixCallback<EntrySalix>(context) {
                override fun onError(t: Throwable) {
                    _entryAdd.value = false
                    super.onError(t)
                }

                override fun onSuccess(response: Response<EntrySalix>) {
                    _entryAdd.value = true
                    super.onSuccess(response)

                }
            })
    }

    fun notificationQueues(notification: String, workerfk: Int, bodyUrl: String) {
        salix.notificationQueues(NotificationQueue(notification, workerfk, bodyUrl))
            .enqueue(object : SalixCallback<Void>(context) {
                override fun onError(t: Throwable) {
                    _responseNotification.value = false
                }

                override fun onSuccess(response: Response<Void>) {
                    _responseNotification.value = true
                    super.onSuccess(response)

                }
            })
    }

    fun getItemsPackaging(supplierId: Int, entryId: Int) {
        salix.getItemsPackaging(supplierId, entryId)
            .enqueue(object : SalixCallback<List<ItemSupplier>>(context) {

                override fun onSuccess(response: Response<List<ItemSupplier>>) {
                    _itemSupplierList.value = response.body()?.let { ItemSupplierList(it) }
                }
            })
    }
}
