package com.pixelized.headache.repository.calendar

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
import javax.inject.Singleton


@Singleton
class GoogleCalendarIdRepository @Inject constructor(
    @param:ApplicationContext private val context: Context,
) {
    val scope = CoroutineScope(Dispatchers.IO)

    // At the top level of your kotlin file:
    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = CALENDAR_ID_STORE)

    val calendarId: StateFlow<Long> = context.dataStore.data
        .map { preferences -> preferences[ID_KEY] ?: ID_DEFAULT }
        .stateIn(
            scope = scope,
            started = SharingStarted.Lazily,
            initialValue = ID_DEFAULT,
        )

    val calendarName: StateFlow<String> = context.dataStore.data
        .map { preferences -> preferences[NAME_KEY] ?: NAME_DEFAULT }
        .stateIn(
            scope = scope,
            started = SharingStarted.Lazily,
            initialValue = NAME_DEFAULT,
        )

    val calendarType: StateFlow<String> = context.dataStore.data
        .map { preferences -> preferences[TYPE_KEY] ?: TYPE_DEFAULT }
        .stateIn(
            scope = scope,
            started = SharingStarted.Lazily,
            initialValue = TYPE_DEFAULT,
        )

    suspend fun toggleCalendar(
        id: Long,
        name: String,
        type: String,
    ) {
        context.dataStore.edit { preferences ->
            preferences[ID_KEY] = id
            preferences[NAME_KEY] = name
            preferences[TYPE_KEY] = type
        }
    }

    companion object Companion {
        private const val CALENDAR_ID_STORE = "CalendarIdStore"
        private const val ID_DEFAULT = 3L
        private const val NAME_DEFAULT = "Céphalée"
        private const val TYPE_DEFAULT = "com.google"
        private val ID_KEY = longPreferencesKey("calendar_id")
        private val NAME_KEY = stringPreferencesKey("calendar_name")
        private val TYPE_KEY = stringPreferencesKey("calendar_type")
    }
}