package org.octopus.internal.common

import org.octopus.internal.common.models.Entry
import java.time.YearMonth
import java.time.ZoneId
import java.util.Date

fun YearMonth.toFirstDayOfMonthDate(zoneId: ZoneId): Date {
    return Date.from(this.atDay(1).atStartOfDay(zoneId).toInstant())
}

fun Date?.isInTargetMonth(yearMonth: YearMonth, zoneId: ZoneId): Boolean {
    if (this == null) return false
    return this.toYearMonth(zoneId).isSame(yearMonth)
}

fun Date.toYearMonth(zoneId: ZoneId = ZoneId.systemDefault()): YearMonth {
    return YearMonth.from(this.toInstant().atZone(zoneId))
}

fun YearMonth.isSame(other: YearMonth): Boolean {
    return this.year == other.year && this.month == other.month
}

fun Date.isSameMonth(other: Date): Boolean {
    val instant1 = this.toInstant()
    val instant2 = other.toInstant()

    val zoneId = ZoneId.systemDefault()

    val yearMonth1 = YearMonth.from(instant1.atZone(zoneId))
    val yearMonth2 = YearMonth.from(instant2.atZone(zoneId))

    return yearMonth1.isSame(yearMonth2)
}

fun Entry.isRecurrentActive(yearMonth: YearMonth, zoneId: ZoneId): Boolean {
    if (this.recurrentMonths?.contains(yearMonth.month) != true) {
        return false
    }

    val startYearMonth = this.startDate?.toYearMonth(zoneId)
    val endYearMonth = this.endDate?.toYearMonth(zoneId)

    val afterStart = startYearMonth == null || !yearMonth.isBefore(startYearMonth)

    val beforeEnd = endYearMonth == null || !yearMonth.isAfter(endYearMonth)

    return afterStart && beforeEnd
}