//
//  TournamentStore.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 26/06/2024.
//

import Foundation
import LeStorage
import SwiftUI

class TournamentStore: Store, ObservableObject {
    
    static func instance(tournamentId: String) -> TournamentStore {
//        if StoreCenter.main.userId == nil {
//            fatalError("cant request store without id")
//        }
        return StoreCenter.main.store(identifier: tournamentId, parameter: "tournament")
    }
    
    fileprivate(set) var groupStages: StoredCollection<GroupStage> = StoredCollection.placeholder()
    fileprivate(set) var matches: StoredCollection<Match> = StoredCollection.placeholder()
    fileprivate(set) var teamRegistrations: StoredCollection<TeamRegistration> = StoredCollection.placeholder()
    fileprivate(set) var playerRegistrations: StoredCollection<PlayerRegistration> = StoredCollection.placeholder()
    fileprivate(set) var rounds: StoredCollection<Round> = StoredCollection.placeholder()
    fileprivate(set) var teamScores: StoredCollection<TeamScore> = StoredCollection.placeholder()

    fileprivate(set) var matchSchedulers: StoredCollection<MatchScheduler> = StoredCollection.placeholder()

    convenience init(tournament: Tournament) {
        self.init(identifier: tournament.id, parameter: "tournament")
    }
    
    required init(identifier: String, parameter: String) {

        super.init(identifier: identifier, parameter: parameter)

        var synchronized: Bool = true
        let indexed: Bool = true

        #if _DEBUG_OPTIONS
        if let sync = PListReader.readBool(plist: "local", key: "synchronized") {
            synchronized = sync
        }
        #endif
        
        self.groupStages = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.rounds = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.teamRegistrations = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.playerRegistrations = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.matches = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.teamScores = self.registerCollection(synchronized: synchronized, indexed: indexed)
        self.matchSchedulers = self.registerCollection(synchronized: false, indexed: indexed)

        self.loadCollectionsFromServerIfNoFile()
        
    }
    
}
