package com.example.timert.data.viewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.example.timert.com.example.timert.data.database.AppDatabase
import com.example.timert.data.entity.Training

import com.example.timert.data.repository.TrainingRepository
import com.example.timert.data.trainingWithExercise

import kotlinx.coroutines.launch

class TrainingViewModel (application: Application): AndroidViewModel(application){

    val allWorkouts: LiveData<List<Training>>
    private val trainingDao = AppDatabase.getDatabase(application).trainingDao()
    private val repository = TrainingRepository(trainingDao)

    val allTrainings: LiveData<List<Training>> = repository.allTrainings
    val allTrainingsWithExercises: LiveData<List<trainingWithExercise>> = repository.allTrainingsWithExercises

    init{
        val trainingDao = AppDatabase.getDatabase(application).trainingDao()

        allWorkouts = repository.allTrainings
    }
    fun insert(training: Training) = viewModelScope.launch {
        repository.insert(training)
    }

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

    fun delete(training: Training) = viewModelScope.launch {
        repository.delete(training)
    }

    fun getTrainingById(id: Int): LiveData<Training> {
        return repository.getTrainingById(id)
    }

    fun insertTrainingAndLinkExercises(training: Training) {
        viewModelScope.launch {
            val newId = repository.insert(training) // возвращает id
            // теперь обновляем trainingId в упражнениях

            AppDatabase.getDatabase(getApplication()).exerciseDao()
                .updateExercisesWithTrainingId(newId.toInt())
        }
    }
}