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

import androidx.compose.ui.graphics.Color
import com.pixelized.headache.repository.calendar.GoogleCalendar
import javax.inject.Inject

class CalendarItemFactory @Inject constructor() {

    fun convertToUio(
        calendars: List<GoogleCalendar>,
        calendarId: Long?,
    ): List<Any> {
        return calendars
            .mapNotNull { calendar ->
                convertToUio(
                    calendar = calendar,
                    used = calendar.id == calendarId,
                )
            }
            .groupBy { it.account }
            .flatMap {
                listOf(it.key) + it.value
            }

    }

    fun convertToUio(
        calendar: GoogleCalendar,
        used: Boolean,
    ): CalendarItemUio? {
        val color = calendar.color.convertToColor() ?: return null

        return CalendarItemUio(
            id = calendar.id,
            name = calendar.name,
            type = calendar.type,
            account = calendar.account,
            color = color,
            used = used,
        )
    }

    fun Int.convertToColor(): Color? = try {
        Color(this)
    } catch (_: Exception) {
        null
    }
}