//
//  Event_v2.swift
//  Padel Tournament
//
//  Created by razmig on 10/03/2024.
//

import Foundation
import LeStorage
import SwiftUI

@Observable
final class Event: BaseEvent {
    
    internal init(creator: String? = nil, club: String? = nil, name: String? = nil, tenupId: String? = nil) {
        super.init(creator: creator, club: club, name: name, tenupId: tenupId)
        self.relatedUser = creator
    }
    
    required init(from decoder: Decoder) throws {
        try super.init(from: decoder)
    }
    
    required public init() {
        super.init()
    }
    
    override func deleteDependencies() {
        let tournaments = self.tournaments
        for tournament in tournaments {
            tournament.deleteDependencies()
        }
        
        DataStore.shared.tournaments.deleteDependencies(tournaments)
        
        let courtsUnavailabilities = self.courtsUnavailability
        for courtsUnavailability in courtsUnavailabilities {
            courtsUnavailability.deleteDependencies()
        }
        DataStore.shared.dateIntervals.deleteDependencies(courtsUnavailabilities)
    }
    
    // MARK: - Computed dependencies
    
    var tournaments: [Tournament] {
        DataStore.shared.tournaments.filter { $0.event == self.id && $0.isDeleted == false }
    }
    
    func clubObject() -> Club? {
        guard let club else { return nil }
        return Store.main.findById(club)
    }
    
    var courtsUnavailability: [DateInterval] {
        DataStore.shared.dateIntervals.filter({ $0.event == id })
    }
    
    // MARK: -
    
    func eventCourtCount() -> Int {
        tournaments.map { $0.courtCount }.max() ?? 2
    }

    func eventStartDate() -> Date {
        tournaments.map { $0.startDate }.min() ?? Date()
    }
    
    func eventDayDuration() -> Int {
        tournaments.map { $0.dayDuration }.max() ?? 1
    }

    func eventTitle() -> String {
        if let name, name.isEmpty == false {
            return name
        } else {
            return "Événement"
        }
    }

    func existingBuild(_ build: any TournamentBuildHolder) -> Tournament? {
        tournaments.first(where: { $0.isSameBuild(build) })
    }
    
    func tournamentsCourtsUsed(exluding tournamentId: String) -> [DateInterval] {
        tournaments.filter { $0.id != tournamentId }.flatMap({ tournament in
            tournament.getPlayedMatchDateIntervals(in: self)
        })
    }
    
    func insertOnServer() throws {
        DataStore.shared.events.writeChangeAndInsertOnServer(instance: self)
        for tournament in self.tournaments {
            try tournament.insertOnServer()
        }
        for dataInterval in self.courtsUnavailability {
            try dataInterval.insertOnServer()
        }
    }
    
}
