package de.sebse.fuplanner2.ui.schedule

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import de.sebse.fuplanner2.database.AppDatabase
import de.sebse.fuplanner2.database.Event
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ScheduleViewModelFactory(): ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel> create(modelClass: Class<T>): T = ScheduleViewModel() as T
}

class ScheduleViewModel() : ViewModel() {
    private val values: HashMap<Int, Event> = hashMapOf()
    private val events: MutableLiveData<List<Event>> = MutableLiveData()

    val eventModel: LiveData<List<Event>>
    get() {
        return events
    }

    fun loadBetween(start: Long, end: Long) {
        GlobalScope.launch {
            withContext(Dispatchers.IO) {
                val data = AppDatabase.getInstance().eventDao().getAllBetween(start, end)
                values.putAll(data.map { it.getHash() to it })
                events.postValue(values.values.toList())
            }
        }
    }
}