//
//  SeedInterval.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/04/2024.
//

import Foundation

struct SeedInterval: Hashable, Comparable {
    let first: Int
    let last: Int
    var reduce: Int = 0
    
    func pointsRange(tournamentLevel: TournamentLevel, teamsCount: Int) -> String {
        let range = [tournamentLevel.points(for: last - 1 - reduce, count: teamsCount),
         tournamentLevel.points(for: first - 1 - reduce, count: teamsCount)]
        return range.map { $0.formatted(.number.sign(strategy: .always())) }.joined(separator: " / ") + " pts"
    }
    
    static func <(lhs: SeedInterval, rhs: SeedInterval) -> Bool {
        return lhs.first < rhs.first
    }
    
    func isFixed() -> Bool {
        first == 1 && last == 2
    }
    
    var count: Int {
        dimension
    }
    
    private var dimension: Int {
        (last - (first - 1))
    }
    
    func chunks() -> [SeedInterval]? {
        if dimension > 3 {
            let split = dimension / 2
            let firstHalf = SeedInterval(first: first, last: first + split - 1, reduce: reduce)
            let secondHalf = SeedInterval(first: first + split, last: last, reduce: reduce)
            return [firstHalf, secondHalf]
        } else {
            return nil
        }
    }

    func localizedLabel(_ displayStyle: DisplayStyle = .wide) -> String {
        if dimension < 2 {
            return "#\(first - reduce) / #\(last - reduce)"
        } else {
            return "#\(first - reduce) à #\(last - reduce)"
        }
    }
}
