You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
PadelClub/PadelClub/Data/GroupStage.swift

112 lines
2.7 KiB

//
// GroupStage_v2.swift
// Padel Tournament
//
// Created by razmig on 10/03/2024.
//
import Foundation
import LeStorage
@Observable
class GroupStage: ModelObject, Storable {
static func resourceName() -> String { "group-stages" }
var id: String = Store.randomId()
var tournament: String
var index: Int
var size: Int
var format: Int?
var startDate: Date?
var matchFormat: MatchFormat {
get {
MatchFormat(rawValue: format ?? 0) ?? .defaultFormatForMatchType(.groupStage)
}
set {
format = newValue.rawValue
}
}
internal init(tournament: String, index: Int, size: Int, matchFormat: MatchFormat? = nil, startDate: Date? = nil) {
self.tournament = tournament
self.index = index
self.size = size
self.format = matchFormat?.rawValue
self.startDate = startDate
}
func tournamentObject() -> Tournament? {
Store.main.findById(tournament)
}
func title(_ displayStyle: DisplayStyle = .wide) -> String {
switch displayStyle {
case .wide:
return "Poule \(index + 1)"
case .short:
return "#\(index + 1)"
}
}
func isBroadcasted() -> Bool {
false
}
func isRunning() -> Bool { // at least a match has started
matches.anySatisfy({ $0.isRunning() })
}
func hasStarted() -> Bool { // meaning at least one match is over
matches.filter { $0.hasEnded() }.isEmpty == false
}
func hasEnded() -> Bool {
if matches.isEmpty { return false }
return matches.allSatisfy { $0.hasEnded() }
}
func buildMatches() {
removeMatches()
var _matches = [Match]()
for i in 0..<numberOfMatchesToBuild {
let newMatch = Match(groupStage: id, index: i, matchFormat: matchFormat)
_matches.append(newMatch)
}
try? DataStore.shared.matches.append(contentOfs: _matches)
}
func removeMatches() {
try? deleteDependencies()
}
var numberOfMatchesToBuild: Int {
(size * (size - 1)) / 2
}
var matches: [Match] {
Store.main.filter { $0.groupStage == self.id }
}
var teams: [TeamRegistration] {
Store.main.filter { $0.groupStage == self.id }
}
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.matches)
}
}
extension GroupStage {
enum CodingKeys: String, CodingKey {
case _id = "id"
case _tournament = "tournament"
case _index = "index"
case _size = "size"
case _format = "format"
case _startDate = "startDate"
}
}