//
//  DrawLog.swift
//  PadelClub
//
//  Created by razmig on 22/10/2024.
//

import Foundation
import SwiftUI
import LeStorage

@Observable
final class DrawLog: BaseDrawLog, SideStorable {
    
    func tournamentObject() -> Tournament? {
        Store.main.findById(self.tournament)
    }
    
    func computedBracketPosition() -> Int {
        drawMatchIndex * 2 + drawTeamPosition.rawValue
    }

    func updateTeamBracketPosition(_ team: TeamRegistration) {
        guard let match = drawMatch() else { return }
        let seedPosition: Int = match.lockAndGetSeedPosition(atTeamPosition: drawTeamPosition)
        team.bracketPosition = seedPosition
        tournamentObject()?.updateTeamScores(in: seedPosition)
    }
    
    func exportedDrawLog() -> String {
        [drawType.localizedDrawType(), drawDate.localizedDate(), localizedDrawLogLabel(), localizedDrawBranch()].filter({ $0.isEmpty == false }).joined(separator: " ")
    }
    
    func localizedDrawSeedLabel() -> String {
        return "\(drawType.localizedDrawType()) #\(drawSeed + 1)"
    }
    
    func localizedDrawLogLabel() -> String {
        return [localizedDrawSeedLabel(), positionLabel()].filter({ $0.isEmpty == false }).joined(separator: " -> ")
    }
    
    func localizedDrawBranch() -> String {
        switch drawType {
        case .seed:
            return drawTeamPosition.localizedBranchLabel()
        default:
            return ""
        }
    }
    
    func drawMatch() -> Match? {
        switch drawType {
        case .seed:
            let roundIndex = RoundRule.roundIndex(fromMatchIndex: drawMatchIndex)
            return tournamentStore?.rounds.first(where: { $0.parent == nil && $0.index == roundIndex })?._matches().first(where: { $0.index == drawMatchIndex })
        default:
            return nil
        }
    }
    
    func positionLabel() -> String {
        return drawMatch()?.roundAndMatchTitle() ?? ""
    }
    
    func roundLabel() -> String {
        return drawMatch()?.roundTitle() ?? ""
    }

    func matchLabel() -> String {
        return drawMatch()?.matchTitle() ?? ""
    }

    var tournamentStore: TournamentStore? {
        return TournamentLibrary.shared.store(tournamentId: self.tournament)
    }

    override func deleteDependencies() {
    }
    
}

enum DrawType: Int, Codable {
    case seed
    case groupStage
    case court
    
    func localizedDrawType() -> String {
        switch self {
        case .seed:
            return "Tête de série"
        case .groupStage:
            return "Poule"
        case .court:
            return "Terrain"
        }
    }
}
