package com.example.timert.data.viewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.timert.com.example.timert.data.database.AppDatabase
import com.example.timert.data.entity.Exercise
import com.example.timert.data.repository.ExerciseRepository
import kotlinx.coroutines.launch

class ExerciseViewModel(application: Application):AndroidViewModel(application){
    private val repository: ExerciseRepository
    val allExercise: LiveData<List<Exercise>>
    private val _unsavedExercises = MutableLiveData<List<Exercise>>(emptyList())
    val unsavedExercises: LiveData<List<Exercise>> = _unsavedExercises
    init{
        val exercisesDao = AppDatabase.getDatabase(application).exerciseDao()
        repository = ExerciseRepository(exercisesDao)
        allExercise = repository.allExercise
    }
    fun insert(exercise: Exercise) = viewModelScope.launch {
        repository.insert(exercise)
    }

    fun deleteExerciseById(id: Int) = viewModelScope.launch {
        repository.deleteExerciseById(id)
    }

    fun getExercisesByTrainingId(trainingId: Int): LiveData<List<Exercise>> {
        return repository.getExercisesByTrainingId(trainingId)
    }

    fun addUnsavedExercise(exercise: Exercise) {
        _unsavedExercises.value = _unsavedExercises.value.orEmpty() + exercise
    }

    fun deleteUnsavedExerciseById(id: Int) {
        _unsavedExercises.value = _unsavedExercises.value.orEmpty().filterNot { it.id == id }
    }

    fun clearUnsavedExercises() {
        _unsavedExercises.value = emptyList()
    }
}