package fr.iut.ouafff.ui.viewmodel

import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import fr.iut.ouafff.data.Dog
import fr.iut.ouafff.data.DogRepository
import fr.iut.ouafff.data.NEW_DOG_ID
import fr.iut.ouafff.data.persistance.DogDatabase
import kotlinx.coroutines.launch
import java.util.Date


class DogViewModel(dogId: Long) : ViewModel() {
    private val dogRepo = DogRepository(DogDatabase.getInstance().dogDAO())

    val dog = if (dogId == NEW_DOG_ID) MutableLiveData(Dog()) else dogRepo.findById(dogId)

    fun saveDog() = dog.value?.let {
        if (it.name.isBlank() || it.weight == 0f)
            false
        else {
            viewModelScope.launch {
                if (it.id == NEW_DOG_ID) dogRepo.insert(it) else dogRepo.update(it)
            }
            true
        }
    }

    fun deleteDog() = viewModelScope.launch {
        dog.value?.let { if (it.id != NEW_DOG_ID) dogRepo.delete(it) }
    }

    val admissionDateLiveData = MediatorLiveData<Date?>()
    init {
        admissionDateLiveData.addSource(dog) { admissionDateLiveData.postValue(it?.admissionDate) }
        admissionDateLiveData.observeForever { newDate ->
            dog.value?.let {
                if (it.admissionDate != newDate)
                    it.admissionDate = newDate
            }
        }
    }

    val ownerLiveData = MediatorLiveData<String?>()
    init {
        ownerLiveData.addSource(dog) { ownerLiveData.postValue(it?.owner) }
        ownerLiveData.observeForever { newOwner ->
            dog.value?.let {
                if (it.owner != newOwner)
                    it.owner = newOwner
            }
        }
    }
}