package de.sebse.fuplanner2.ui.tools.viewmodels

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import androidx.work.workDataOf
import de.sebse.fuplanner2.auth.AppAccounts
import de.sebse.fuplanner2.database.Announcement
import de.sebse.fuplanner2.database.AppDatabase
import de.sebse.fuplanner2.database.Course
import de.sebse.fuplanner2.database.Event
import de.sebse.fuplanner2.utils.enqueueOneTimeWork
import de.sebse.fuplanner2.worker.AbstractAccountWorker
import de.sebse.fuplanner2.worker.CourseWorker


class DetailsViewModelFactory(private val courseId: Long): ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel> create(modelClass: Class<T>): T = DetailsViewModel(courseId) as T
}

class DetailsViewModel(private val courseId: Long) : ViewModel() {
    fun refresh(ctx: Context) {
        enqueueOneTimeWork<CourseWorker>(ctx) {
            it.setInputData(workDataOf(
                    AbstractAccountWorker.KEY_ACCOUNT_NAME to AppAccounts.getInstance().selectedAccount?.name,
                    AbstractAccountWorker.KEY_COURSE_ID to courseId,
                    AbstractAccountWorker.KEY_FORCE_FETCH to true
                )
            )
        }
    }

    val course: LiveData<Course> = AppDatabase.getInstance().courseDao().getCourseById(courseId)
    val announcements: LiveData<PagedList<Announcement>> = LivePagedListBuilder(
        AppDatabase.getInstance().announcementDao().getAll1(courseId),
        50
    ).build()
    val events: LiveData<PagedList<Event>> = LivePagedListBuilder(
        AppDatabase.getInstance().eventDao().getAll1(courseId),
        50
    ).build()
}
