package com.xd.roomdatabasekotlin

import android.app.Application
import androidx.lifecycle.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException


class CommentViewModel(private val repository: CommentRepository) : ViewModel() {
    val allCommentsLiveData: LiveData<List<Comment>> = repository.allComments.asLiveData()

    fun insert(comment: Comment) {
        repository.insert(comment)
    }

    fun deleteFirst(){
        val commentList = allCommentsLiveData.value
        if (commentList != null && commentList.size > 0){
            val id = commentList[0].id
            repository.delete(id)
        }
    }

    fun deleteAll(){
        val commentList = allCommentsLiveData.value
        if (commentList != null && commentList.size > 0)
            repository.deleteAll()
    }
}

class CommentViewModelFactory (private val repository: CommentRepository) : ViewModelProvider.Factory {
    override fun<T: ViewModel> create(modelClass: Class<T>) : T{ //create() creates a new instance of the modelClass, which is CommentViewModel in this case.
        if(modelClass.isAssignableFrom(CommentViewModel::class.java))
            return CommentViewModel(repository) as T
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}