//
//  Calendar+Extensions.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 28/03/2024.
//

import Foundation

extension Calendar {
    func numberOfDaysBetween(_ from: Date?, and to: Date?) -> Int {
        guard let from, let to else { return 0 }
        let fromDate = startOfDay(for: from)
        let toDate = startOfDay(for: to)
        let numberOfDays = dateComponents([.day], from: fromDate, to: toDate)
        
        return numberOfDays.day! // <1>
    }
    
    func isSameDay(date1: Date?, date2: Date?) -> Bool {
        guard let date1, let date2 else { return false }
        
        return numberOfDaysBetween(date1, and: date2) == 0
    }

    func getSportAge() -> Int {
        let currentDate = Date()
        
        // Get the current year
        let currentYear = component(.year, from: currentDate)
        
        // Define the date components for 1st September and 31st December of the current year
        let septemberFirstComponents = DateComponents(year: currentYear, month: 9, day: 1)
        let decemberThirtyFirstComponents = DateComponents(year: currentYear, month: 12, day: 31)
        
        // Get the actual dates for 1st September and 31st December
        let septemberFirst = date(from: septemberFirstComponents)!
        let decemberThirtyFirst = date(from: decemberThirtyFirstComponents)!
        
        // Determine the sport year
        let sportYear: Int
        if currentDate >= septemberFirst && currentDate <= decemberThirtyFirst {
            // If after 1st September and before 31st December, use current year + 1
            sportYear = currentYear + 1
        } else {
            // Otherwise, use the current year
            sportYear = currentYear
        }
        return sportYear
    }
}

extension Calendar {
    // Add or subtract months from a date
    func addMonths(_ months: Int, to date: Date) -> Date {
        return self.date(byAdding: .month, value: months, to: date)!
    }
    
    // Generate a list of month start dates between two dates
    func generateMonthRange(startDate: Date, endDate: Date) -> [Date] {
        var dates: [Date] = []
        var currentDate = startDate
        
        while currentDate <= endDate {
            dates.append(currentDate)
            currentDate = self.addMonths(1, to: currentDate)
        }
        
        return dates
    }
}
