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

import Foundation
import LeStorage
import SwiftUI

class TournamentStore: ObservableObject {
    
    var store: Store
    
    fileprivate(set) var groupStages: SyncedCollection<GroupStage> = SyncedCollection.placeholder()
    fileprivate(set) var matches: SyncedCollection<Match> = SyncedCollection.placeholder()
    fileprivate(set) var teamRegistrations: SyncedCollection<TeamRegistration> = SyncedCollection.placeholder()
    fileprivate(set) var playerRegistrations: SyncedCollection<PlayerRegistration> = SyncedCollection.placeholder()
    fileprivate(set) var rounds: SyncedCollection<Round> = SyncedCollection.placeholder()
    fileprivate(set) var teamScores: SyncedCollection<TeamScore> = SyncedCollection.placeholder()

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

//    convenience init(tournament: Tournament) {
//        let store = StoreCenter.main.store(identifier: tournament.id)
//        self.init(store: store)
//        self._initialize()
//    }

    init(store: Store) {
        self.store = store
        self._initialize()
    }
    
    fileprivate func _initialize() {

        let indexed: Bool = true

        self.groupStages = self.store.registerSynchronizedCollection(indexed: indexed)
        self.rounds = self.store.registerSynchronizedCollection(indexed: indexed)
        self.teamRegistrations = self.store.registerSynchronizedCollection(indexed: indexed)
        self.playerRegistrations = self.store.registerSynchronizedCollection(indexed: indexed)
        self.matches = self.store.registerSynchronizedCollection(indexed: indexed)
        self.teamScores = self.store.registerSynchronizedCollection(indexed: indexed)
        self.matchSchedulers = self.store.registerCollection(indexed: indexed)
        self.drawLogs = self.store.registerSynchronizedCollection(indexed: indexed)

        self.store.loadCollectionsFromServerIfNoFile()
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(_leStorageDidSynchronize),
            name: NSNotification.Name.LeStorageDidSynchronize,
            object: nil)

    }
    
    @objc func _leStorageDidSynchronize(notification: Notification) {
//        Logger.log("SYNCED > teamRegistrations count = \(self.teamRegistrations.count)")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
