package com.pixelized.headache.ui.page.calendar

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.headache.repository.calendar.GoogleCalendarIdRepository
import com.pixelized.headache.repository.calendar.GoogleCalendarRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class CalendarViewModel @Inject constructor(
    private val calendarIdRepository: GoogleCalendarIdRepository,
    calendarRepository: GoogleCalendarRepository,
    calendarItemFactory: CalendarItemFactory,
) : ViewModel() {

    val calendars: StateFlow<List<Any>> = combine(
        calendarRepository.calendarFlow,
        calendarIdRepository.calendarId,
    ) { calendars, calendarId ->
        calendarItemFactory.convertToUio(
            calendars = calendars,
            calendarId = calendarId,
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.Lazily,
        initialValue = emptyList(),
    )

    suspend fun toggleCalendar(
        id: Long,
        name: String,
        type: String,
    ) {
        calendarIdRepository.toggleCalendar(
            id = id,
            name = name,
            type = type,
        )
    }
}