package com.pixelized.headache.repository.calendar

import android.content.Context
import android.provider.CalendarContract
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class GoogleCalendarRepository @Inject constructor(
    @param:ApplicationContext private val context: Context,
) {
    private val _calendarFlow = MutableStateFlow(listCalendars())
    val calendarFlow: StateFlow<List<GoogleCalendar>> = _calendarFlow

    private fun listCalendars(): List<GoogleCalendar> {
        val calendars = mutableListOf<GoogleCalendar>()
        val projection = arrayOf(
            CalendarContract.Calendars._ID,
            CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
            CalendarContract.Calendars.ACCOUNT_NAME,
            CalendarContract.Calendars.ACCOUNT_TYPE,
            CalendarContract.Calendars.CALENDAR_COLOR,
        )
        val cursor = context.contentResolver.query(
            CalendarContract.Calendars.CONTENT_URI,
            projection,
            null,
            null,
            null
        )

        cursor?.use {
            val idIdx = it.getColumnIndex(CalendarContract.Calendars._ID)
            val nameIdx = it.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)
            val accountIdx = it.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME)
            val typeIdx = it.getColumnIndex(CalendarContract.Calendars.ACCOUNT_TYPE)
            val colorIdx = it.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR)

            while (it.moveToNext()) {
                val calendar = GoogleCalendar(
                    id = it.getLong(idIdx),
                    name = it.getString(nameIdx),
                    account = it.getString(accountIdx),
                    type = it.getString(typeIdx),
                    color = it.getInt(colorIdx),
                )
                calendars.add(calendar)
            }
        }
        return calendars
    }
}