//
//  DateInterval.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 19/04/2024.
//

import Foundation
import SwiftUI
import LeStorage

@Observable
class DateInterval: ModelObject, Storable {
    static func resourceName() -> String { return "date-intervals" }
    static func tokenExemptedMethods() -> [HTTPMethod] { return [] }

    var id: String = Store.randomId()
    var event: String
    var courtIndex: Int
    var startDate: Date
    var endDate: Date

    internal init(event: String, courtIndex: Int, startDate: Date, endDate: Date) {
        self.event = event
        self.courtIndex = courtIndex
        self.startDate = startDate
        self.endDate = endDate
    }
    
    var range: Range<Date> {
        startDate..<endDate
    }
    
    func isSingleDay() -> Bool {
        Calendar.current.isDate(startDate, inSameDayAs: endDate)
    }

    func isDateInside(_ date: Date) -> Bool {
        date >= startDate && date <= endDate
    }

    func isDateOutside(_ date: Date) -> Bool {
        date <= startDate && date <= endDate && date >= startDate && date >= endDate
    }
    
    override func deleteDependencies() throws {
    }
    
    enum CodingKeys: String, CodingKey {
        case _id = "id"
        case _event = "event"
        case _courtIndex = "courtIndex"
        case _startDate = "startDate"
        case _endDate = "endDate"
    }
    
    func insertOnServer() throws {
        try DataStore.shared.dateIntervals.writeChangeAndInsertOnServer(instance: self)
    }
    
}
