package dominando.android.presentation

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import dominando.android.domain.SaveBookUseCase
import dominando.android.presentation.binding.BookConverter
import java.io.File
import dominando.android.presentation.binding.Book as BookBinding

class BookFormViewModel(private val useCase: SaveBookUseCase) : ViewModel() {
    var book: BookBinding? = null
    var tempImageFile: File? = null
        set(value) {
            deleteTempPhoto()
            field = value
            shouldDeleteImage = true
        }
    private var shouldDeleteImage: Boolean = true

    private var showProgress = MutableLiveData<Boolean>().apply {
        value = false
    }
    private var saveBook = MutableLiveData<BookBinding>()
    private var savingBookOperation: LiveData<SaveResult> =
            Transformations.switchMap(saveBook) { bookBinding ->
                val book = BookConverter.toData(bookBinding)
                Transformations.map(useCase.saveBook(book)) { result ->

                    showProgress.value = false
                    if (result is SaveBookUseCase.Result.Success) {
                        shouldDeleteImage = false
                        tempImageFile = null
                    }
                    SaveResult.fromResult(result)
                }
            }

    fun showProgress(): LiveData<Boolean> = showProgress
    fun savingOperation(): LiveData<SaveResult> = savingBookOperation

    fun saveBook(book: BookBinding) {
        showProgress.value = true
        saveBook.value = book
    }

    private fun deleteTempPhoto() {
        if (shouldDeleteImage) {
            tempImageFile?.let {
                if (it.exists()) it.delete()
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        deleteTempPhoto()
    }

    enum class SaveResult {
        SUCCESS,
        INVALID_TITLE,
        INVALID_AUTHOR,
        INVALID_YEAR,
        INVALID_PAGES,
        GENERIC_ERROR;

        companion object {
            fun fromResult(result: SaveBookUseCase.Result): SaveResult {
                return when(result) {
                    is SaveBookUseCase.Result.Success -> SUCCESS
                    is SaveBookUseCase.Result.InvalidTitle -> INVALID_TITLE
                    is SaveBookUseCase.Result.InvalidAuthor -> INVALID_AUTHOR
                    is SaveBookUseCase.Result.InvalidYear -> INVALID_YEAR
                    is SaveBookUseCase.Result.InvalidPages -> INVALID_PAGES
                    else -> GENERIC_ERROR
                }
            }
        }
    }
}