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.
946 lines
38 KiB
946 lines
38 KiB
//
|
|
// PlanningView.swift
|
|
// PadelClub
|
|
//
|
|
// Created by Razmig Sarkissian on 07/04/2024.
|
|
//
|
|
|
|
import LeStorage
|
|
import PadelClubData
|
|
import SwiftUI
|
|
import TipKit
|
|
|
|
struct PlanningView: View {
|
|
|
|
@EnvironmentObject var dataStore: DataStore
|
|
@State private var selectedDay: Date?
|
|
@Binding var selectedScheduleDestination: ScheduleDestination?
|
|
@State private var filterOption: PlanningFilterOption = .byDefault
|
|
@State private var showFinishedMatches: Bool = false
|
|
@State private var enableMove: Bool = false
|
|
@Environment(\.editMode) private var editMode
|
|
let updatePlannedDatesTip = UpdatePlannedDatesTip()
|
|
let allMatches: [Match]
|
|
let timeSlotMoveOptionTip = TimeSlotMoveOptionTip()
|
|
|
|
init(matches: [Match], selectedScheduleDestination: Binding<ScheduleDestination?>) {
|
|
self.allMatches = matches
|
|
_selectedScheduleDestination = selectedScheduleDestination
|
|
}
|
|
|
|
var matches: [Match] {
|
|
allMatches.filter({ showFinishedMatches || $0.endDate == nil })
|
|
}
|
|
|
|
var timeSlots: [Date: [Match]] {
|
|
Dictionary(grouping: matches) { $0.plannedStartDate ?? $0.startDate ?? .distantFuture }
|
|
}
|
|
|
|
func days(timeSlots: [Date: [Match]]) -> [Date] {
|
|
Set(timeSlots.keys.map { $0.startOfDay }).sorted()
|
|
}
|
|
|
|
func keys(timeSlots: [Date: [Match]]) -> [Date] {
|
|
timeSlots.keys.sorted()
|
|
}
|
|
|
|
private func _computedTitle(days: [Date]) -> String {
|
|
if let selectedDay {
|
|
return selectedDay.formatted(.dateTime.day().weekday().month())
|
|
} else {
|
|
if days.count > 1 {
|
|
return "Tous les jours"
|
|
} else {
|
|
return "Horaires"
|
|
}
|
|
}
|
|
}
|
|
|
|
private func _confirmationMode() -> Bool {
|
|
enableMove || editMode?.wrappedValue == .active
|
|
}
|
|
|
|
private var enableEditionBinding: Binding<Bool> {
|
|
Binding {
|
|
editMode?.wrappedValue == .active
|
|
} set: { value in
|
|
if value {
|
|
editMode?.wrappedValue = .active
|
|
} else {
|
|
editMode?.wrappedValue = .inactive
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
var body: some View {
|
|
let timeSlots = self.timeSlots
|
|
let keys = self.keys(timeSlots: timeSlots)
|
|
let days = self.days(timeSlots: timeSlots)
|
|
let matches = matches
|
|
let notSlots = matches.allSatisfy({ $0.startDate == nil })
|
|
BySlotView(
|
|
days: days, keys: keys, timeSlots: timeSlots, matches: matches, selectedDay: selectedDay
|
|
)
|
|
.environment(\.filterOption, filterOption)
|
|
.environment(\.showFinishedMatches, showFinishedMatches)
|
|
.environment(\.enableMove, enableMove)
|
|
.navigationTitle(Text(_computedTitle(days: days)))
|
|
.navigationBarBackButtonHidden(_confirmationMode())
|
|
.toolbar(content: {
|
|
if days.count > 1 {
|
|
ToolbarTitleMenu {
|
|
Picker(selection: $selectedDay) {
|
|
Text("Tous les jours").tag(nil as Date?)
|
|
ForEach(days, id: \.self) { day in
|
|
if day.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
Text("Sans horaire").tag(day as Date?)
|
|
} else {
|
|
Text(day.formatted(.dateTime.day().weekday().month())).tag(
|
|
day as Date?)
|
|
}
|
|
}
|
|
} label: {
|
|
Text("Jour")
|
|
}
|
|
.pickerStyle(.automatic)
|
|
.disabled(_confirmationMode())
|
|
}
|
|
}
|
|
|
|
if _confirmationMode() {
|
|
ToolbarItem(placement: .topBarLeading) {
|
|
Button(enableMove ? "Annuler" : "Terminer") {
|
|
enableMove = false
|
|
enableEditionBinding.wrappedValue = false
|
|
}
|
|
}
|
|
if enableMove {
|
|
ToolbarItemGroup(placement: .topBarTrailing) {
|
|
Button("Sauver") {
|
|
let groupByTournaments = allMatches.grouped { match in
|
|
match.currentTournament()
|
|
}
|
|
groupByTournaments.forEach { tournament, matches in
|
|
tournament?.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
}
|
|
|
|
enableMove = false
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
ToolbarItemGroup(placement: .topBarTrailing) {
|
|
Menu {
|
|
if notSlots == false {
|
|
CourtOptionsView(timeSlots: timeSlots, underlined: false)
|
|
Toggle(isOn: $enableMove) {
|
|
Label {
|
|
Text("Déplacer un créneau")
|
|
} icon: {
|
|
Image(systemName: "rectangle.2.swap")
|
|
}
|
|
}
|
|
.popoverTip(timeSlotMoveOptionTip)
|
|
.disabled(_confirmationMode())
|
|
Toggle(isOn: enableEditionBinding) {
|
|
Text("Modifier un horaire")
|
|
}
|
|
.disabled(_confirmationMode())
|
|
}
|
|
|
|
Divider()
|
|
|
|
Menu {
|
|
Section {
|
|
Picker(selection: $showFinishedMatches) {
|
|
Text("Afficher tous les matchs").tag(true)
|
|
Text("Masquer les matchs terminés").tag(false)
|
|
} label: {
|
|
Text("Option de filtrage")
|
|
}
|
|
.labelsHidden()
|
|
.pickerStyle(.inline)
|
|
} header: {
|
|
Text("Option de filtrage")
|
|
}
|
|
|
|
Divider()
|
|
|
|
Section {
|
|
Picker(selection: $filterOption) {
|
|
ForEach(PlanningFilterOption.allCases) {
|
|
Text($0.localizedPlanningLabel()).tag($0)
|
|
}
|
|
} label: {
|
|
Text("Option de triage")
|
|
}
|
|
.labelsHidden()
|
|
.pickerStyle(.inline)
|
|
} header: {
|
|
Text("Option de triage")
|
|
|
|
}
|
|
} label: {
|
|
Label("Trier", systemImage: "line.3.horizontal.decrease.circle")
|
|
.symbolVariant(
|
|
filterOption == .byCourt || showFinishedMatches ? .fill : .none)
|
|
}
|
|
|
|
Divider()
|
|
|
|
Button("Mettre à jour", systemImage: "arrow.trianglehead.2.clockwise.rotate.90.circle") {
|
|
let now = Date()
|
|
matches.forEach {
|
|
if let startDate = $0.startDate, startDate > now {
|
|
$0.plannedStartDate = $0.startDate
|
|
}
|
|
}
|
|
|
|
let groupByTournaments = matches.grouped { match in
|
|
match.currentTournament()
|
|
}
|
|
groupByTournaments.forEach { tournament, matches in
|
|
tournament?.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
}
|
|
}
|
|
.popoverTip(updatePlannedDatesTip)
|
|
|
|
|
|
} label: {
|
|
LabelOptions()
|
|
}
|
|
}
|
|
}
|
|
})
|
|
.overlay {
|
|
if notSlots {
|
|
ContentUnavailableView {
|
|
Label("Aucun horaire défini", systemImage: "clock.badge.questionmark")
|
|
} description: {
|
|
Text(
|
|
"Vous n'avez pas encore défini d'horaire pour les différentes phases du tournoi"
|
|
)
|
|
} actions: {
|
|
if selectedScheduleDestination != nil {
|
|
RowButtonView("Horaire intelligent") {
|
|
selectedScheduleDestination = nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
struct BySlotView: View {
|
|
@Environment(\.filterOption) private var filterOption
|
|
@Environment(\.showFinishedMatches) private var showFinishedMatches
|
|
@Environment(\.enableMove) private var enableMove
|
|
@Environment(\.editMode) private var editMode
|
|
@State private var selectedIds = Set<String>()
|
|
@State private var showDateUpdateView: Bool = false
|
|
@State private var matchesToUpdate: [Match] = []
|
|
|
|
let days: [Date]
|
|
let keys: [Date]
|
|
let timeSlots: [Date: [Match]]
|
|
let matches: [Match]
|
|
let selectedDay: Date?
|
|
let timeSlotMoveTip = TimeSlotMoveTip()
|
|
|
|
var body: some View {
|
|
List(selection: $selectedIds) {
|
|
if enableMove {
|
|
TipView(timeSlotMoveTip)
|
|
.tipStyle(tint: .logoYellow, asSection: true)
|
|
}
|
|
|
|
if !matches.allSatisfy({ $0.startDate == nil }) {
|
|
ForEach(days.filter({ selectedDay == nil || selectedDay == $0 }), id: \.self) {
|
|
day in
|
|
DaySectionView(
|
|
day: day,
|
|
keys: keys.filter({ $0.dayInt == day.dayInt }),
|
|
timeSlots: timeSlots,
|
|
selectedDay: selectedDay,
|
|
selectedIds: $selectedIds,
|
|
matchesForUpdateSheet: $matchesToUpdate
|
|
)
|
|
}
|
|
}
|
|
}
|
|
.toolbar(content: {
|
|
if editMode?.wrappedValue == .active {
|
|
ToolbarItem(placement: .topBarTrailing) {
|
|
Button {
|
|
matchesToUpdate = matches.filter({ selectedIds.contains($0.stringId) })
|
|
} label: {
|
|
Text("Modifier")
|
|
}
|
|
.buttonStyle(.borderless)
|
|
.disabled(selectedIds.isEmpty)
|
|
}
|
|
}
|
|
})
|
|
.onChange(of: matchesToUpdate, { oldValue, newValue in
|
|
showDateUpdateView = matchesToUpdate.count > 0
|
|
})
|
|
.sheet(isPresented: $showDateUpdateView, onDismiss: {
|
|
selectedIds.removeAll()
|
|
matchesToUpdate = []
|
|
}) {
|
|
DateUpdateView(selectedMatches: matchesToUpdate)
|
|
}
|
|
}
|
|
}
|
|
|
|
struct DateUpdateView: View {
|
|
@Environment(\.dismiss) var dismiss
|
|
|
|
let selectedMatches: [Match]
|
|
let selectedFormats: [MatchFormat]
|
|
@State private var dateToUpdate: Date
|
|
@State private var updateStep: Int = 0
|
|
|
|
init(selectedMatches: [Match]) {
|
|
self.selectedMatches = selectedMatches
|
|
self.selectedFormats = Array(Set(selectedMatches.map({ match in
|
|
match.matchFormat
|
|
})))
|
|
_dateToUpdate = .init(wrappedValue: selectedMatches.first?.plannedStartDate ?? selectedMatches.first?.startDate ?? Date())
|
|
}
|
|
|
|
var body: some View {
|
|
NavigationStack {
|
|
List {
|
|
Section {
|
|
DatePicker(selection: $dateToUpdate) {
|
|
Text(dateToUpdate.formatted(.dateTime.weekday(.wide))).font(.headline)
|
|
}
|
|
|
|
RowButtonView("Définir le nouvel horaire", role: .destructive) {
|
|
_setDate()
|
|
}
|
|
} footer: {
|
|
Text("Choisir un nouvel horaire pour tous les matchs sélectionnés")
|
|
}
|
|
|
|
Section {
|
|
LabeledContent {
|
|
StepperView(title: "minutes", count: $updateStep, step: 5)
|
|
} label: {
|
|
Text("Décalage")
|
|
}
|
|
|
|
RowButtonView("Décaler les horaires", role: .destructive) {
|
|
_updateDate()
|
|
}
|
|
|
|
} footer: {
|
|
Text("décale CHAQUE horaire du nombre de minutes indiqué")
|
|
.foregroundStyle(.logoRed)
|
|
}
|
|
|
|
VStack {
|
|
StepAdjusterView(step: $updateStep)
|
|
Divider()
|
|
StepAdjusterView(step: $updateStep, time: 10)
|
|
ForEach(selectedFormats, id: \.self) { matchFormat in
|
|
Divider()
|
|
StepAdjusterView(step: $updateStep, matchFormat: matchFormat)
|
|
}
|
|
}
|
|
|
|
Section {
|
|
ForEach(selectedMatches) { match in
|
|
MatchRowView(match: match)
|
|
}
|
|
} header: {
|
|
Text("Matchs à modifier")
|
|
}
|
|
|
|
}
|
|
.onChange(of: updateStep, { oldValue, newValue in
|
|
dateToUpdate.addTimeInterval(TimeInterval((newValue - oldValue) * 60))
|
|
})
|
|
.navigationTitle("Modifier l'horaire")
|
|
.navigationBarTitleDisplayMode(.inline)
|
|
.toolbarBackground(.visible, for: .navigationBar)
|
|
.toolbar(content: {
|
|
ToolbarItem(placement: .topBarLeading) {
|
|
Button("Annuler", role: .cancel) {
|
|
dismiss()
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
private func _updateDate() {
|
|
selectedMatches.forEach { match in
|
|
if match.hasStarted() || match.hasEnded() {
|
|
match.plannedStartDate?.addTimeInterval(TimeInterval(updateStep * 60))
|
|
} else {
|
|
match.startDate?.addTimeInterval(TimeInterval(updateStep * 60))
|
|
}
|
|
}
|
|
|
|
let groupByTournaments = selectedMatches.grouped { match in
|
|
match.currentTournament()
|
|
}
|
|
groupByTournaments.forEach { tournament, matches in
|
|
tournament?.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
}
|
|
dismiss()
|
|
}
|
|
|
|
private func _setDate() {
|
|
selectedMatches.forEach { match in
|
|
if match.hasStarted() || match.hasEnded() {
|
|
match.plannedStartDate = dateToUpdate
|
|
} else {
|
|
match.startDate = dateToUpdate
|
|
}
|
|
}
|
|
|
|
let groupByTournaments = selectedMatches.grouped { match in
|
|
match.currentTournament()
|
|
}
|
|
groupByTournaments.forEach { tournament, matches in
|
|
tournament?.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
}
|
|
dismiss()
|
|
}
|
|
|
|
}
|
|
|
|
|
|
struct DaySectionView: View {
|
|
@Environment(\.filterOption) private var filterOption
|
|
@Environment(\.showFinishedMatches) private var showFinishedMatches
|
|
@Environment(\.enableMove) private var enableMove
|
|
@Environment(\.editMode) private var editMode
|
|
|
|
let day: Date
|
|
let keys: [Date]
|
|
let timeSlots: [Date: [Match]]
|
|
let selectedDay: Date?
|
|
@Binding var selectedIds: Set<String>
|
|
@State private var selectAll: Bool = false
|
|
@Binding var matchesForUpdateSheet: [Match]
|
|
|
|
var body: some View {
|
|
Section {
|
|
ForEach(keys, id: \.self) { key in
|
|
TimeSlotSectionView(
|
|
key: key,
|
|
matches: timeSlots[key]?.sorted(
|
|
by: filterOption == .byDefault
|
|
? \.computedOrder : \.courtIndexForSorting) ?? [], matchesForUpdateSheet: $matchesForUpdateSheet
|
|
)
|
|
}
|
|
.onMove(perform: enableMove ? moveSection : nil)
|
|
} header: {
|
|
if editMode?.wrappedValue == .active {
|
|
HStack {
|
|
Spacer()
|
|
FooterButtonView(selectAll ? "Tout desélectionner" : "Tout sélectionner") {
|
|
selectAll.toggle()
|
|
}
|
|
.textCase(nil)
|
|
}
|
|
} else {
|
|
HeaderView(day: day, timeSlots: timeSlots)
|
|
}
|
|
} footer: {
|
|
VStack(alignment: .leading) {
|
|
if day.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
Text(
|
|
"Il s'agit des matchs qui n'ont pas réussi à être placé par Padel Club. Peut-être à cause de créneaux indisponibles, d'autres tournois ou des réglages."
|
|
)
|
|
}
|
|
|
|
CourtOptionsView(timeSlots: timeSlots, underlined: true)
|
|
}
|
|
}
|
|
.onChange(of: selectAll, { oldValue, newValue in
|
|
if oldValue == false, newValue == true {
|
|
selectedIds = Set(timeSlots.filter({ keys.contains($0.key) }).values.flatMap({ values in values.compactMap({ match in match.stringId }) }))
|
|
} else if oldValue == true, newValue == false {
|
|
selectedIds.removeAll()
|
|
}
|
|
})
|
|
.onChange(of: editMode?.wrappedValue) { oldValue, newValue in
|
|
selectAll = false
|
|
}
|
|
}
|
|
|
|
func moveSection(from source: IndexSet, to destination: Int) {
|
|
let daySlots = keys.filter { $0.dayInt == day.dayInt }.sorted()
|
|
|
|
guard let sourceIdx = source.first,
|
|
sourceIdx < daySlots.count,
|
|
destination <= daySlots.count
|
|
else {
|
|
return
|
|
}
|
|
|
|
// Create a mutable copy of the time slots for this day
|
|
var slotsToUpdate = daySlots
|
|
|
|
let updateRange = min(sourceIdx, destination)...max(sourceIdx, destination)
|
|
|
|
// Perform the move in the array
|
|
let sourceTime = slotsToUpdate.remove(at: sourceIdx)
|
|
if sourceIdx < destination {
|
|
slotsToUpdate.insert(sourceTime, at: destination - 1)
|
|
} else {
|
|
slotsToUpdate.insert(sourceTime, at: destination)
|
|
}
|
|
|
|
// Update matches by swapping their startDates
|
|
for index in updateRange {
|
|
// Find the new time slot for these matches
|
|
guard let oldStartTime = slotsToUpdate[safe: index] else { continue }
|
|
guard let newStartTime = daySlots[safe: index] else { continue }
|
|
guard let matchesToUpdate = timeSlots[oldStartTime] else { continue }
|
|
|
|
// Update each match with the new start time
|
|
for match in matchesToUpdate {
|
|
match.startDate = newStartTime
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
struct TimeSlotSectionView: View {
|
|
@Environment(\.enableMove) private var enableMove
|
|
@Environment(\.editMode) private var editMode
|
|
let key: Date
|
|
let matches: [Match]
|
|
|
|
@State private var isExpanded: Bool = false
|
|
@Binding var matchesForUpdateSheet: [Match]
|
|
|
|
var body: some View {
|
|
if !matches.isEmpty {
|
|
if enableMove {
|
|
TimeSlotHeaderView(key: key, matches: matches)
|
|
} else {
|
|
DisclosureGroup(isExpanded: $isExpanded) {
|
|
MatchListView(matches: matches)
|
|
} label: {
|
|
TimeSlotHeaderView(key: key, matches: matches)
|
|
}
|
|
.onChange(of: editMode?.wrappedValue, { oldValue, newValue in
|
|
if oldValue == .inactive, newValue == .active, isExpanded == false {
|
|
isExpanded = true
|
|
} else if oldValue == .active, newValue == .inactive, isExpanded == true {
|
|
isExpanded = false
|
|
}
|
|
})
|
|
.contextMenu {
|
|
PlanningView.CourtOptionsView(timeSlots: [key: matches], underlined: false)
|
|
|
|
Button {
|
|
matchesForUpdateSheet = matches
|
|
} label: {
|
|
Text("Modifier la date")
|
|
}
|
|
|
|
}
|
|
// .onChange(of: editMode?.wrappedValue) {
|
|
// if editMode?.wrappedValue == .active, isExpanded == false {
|
|
// isExpanded = true
|
|
// } else if editMode?.wrappedValue == .inactive, isExpanded == true {
|
|
// isExpanded = false
|
|
// }
|
|
// }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
struct MatchListView: View {
|
|
let matches: [Match]
|
|
|
|
var body: some View {
|
|
ForEach(matches, id: \.stringId) { match in
|
|
NavigationLink {
|
|
MatchDetailView(match: match)
|
|
.matchViewStyle(.sectionedStandardStyle)
|
|
} label: {
|
|
MatchRowView(match: match)
|
|
}
|
|
.listRowView(isActive: match.hasStarted(), color: .green, hideColorVariation: true)
|
|
}
|
|
}
|
|
}
|
|
|
|
struct MatchRowView: View {
|
|
@Environment(\.matchViewStyle) private var matchViewStyle
|
|
let match: Match
|
|
|
|
var body: some View {
|
|
LabeledContent {
|
|
VStack(alignment: .center) {
|
|
if let courtName = match.courtName() {
|
|
Text(courtName).foregroundStyle(.primary)
|
|
}
|
|
Text(match.matchFormat.shortFormat + " (~" + match.getDuration().formatted() + "m)").font(.footnote).foregroundStyle(.tertiary)
|
|
}
|
|
} label: {
|
|
if let groupStage = match.groupStageObject {
|
|
Text(groupStage.groupStageTitle(.title))
|
|
Text(match.matchTitle())
|
|
} else if let round = match.roundObject {
|
|
Text(round.roundTitle())
|
|
if round.index > 0 {
|
|
Text(match.matchTitle())
|
|
}
|
|
}
|
|
if matchViewStyle == .feedStyle, let tournament = match.currentTournament() {
|
|
Text(tournament.tournamentTitle())
|
|
}
|
|
|
|
Text(match.startDate?.formattedAsHourMinute() ?? "--")
|
|
}
|
|
}
|
|
}
|
|
|
|
struct HeaderView: View {
|
|
@Environment(\.filterOption) private var filterOption
|
|
@Environment(\.showFinishedMatches) private var showFinishedMatches
|
|
@Environment(\.enableMove) private var enableMove
|
|
|
|
let day: Date
|
|
let timeSlots: [Date: [Match]]
|
|
|
|
var body: some View {
|
|
HStack {
|
|
if day.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
Text("Sans horaire")
|
|
} else {
|
|
Text(day.formatted(.dateTime.day().weekday().month()))
|
|
}
|
|
Spacer()
|
|
let count = _matchesCount(inDayInt: day.dayInt, timeSlots: timeSlots)
|
|
if showFinishedMatches {
|
|
Text(_formattedMatchCount(count))
|
|
} else {
|
|
Text("\(_formattedMatchCount(count)) restant\(count.pluralSuffix)")
|
|
}
|
|
}
|
|
}
|
|
|
|
private func _matchesCount(inDayInt dayInt: Int, timeSlots: [Date: [Match]]) -> Int {
|
|
timeSlots.filter { $0.key.dayInt == dayInt }.flatMap({ $0.value }).count
|
|
}
|
|
|
|
private func _formattedMatchCount(_ count: Int) -> String {
|
|
return "\(count.formatted()) match\(count.pluralSuffix)"
|
|
}
|
|
}
|
|
|
|
struct TimeSlotHeaderView: View {
|
|
let key: Date
|
|
let matches: [Match]
|
|
|
|
var body: some View {
|
|
LabeledContent {
|
|
Text("\(matches.count.formatted()) match\(matches.count.pluralSuffix)")
|
|
} label: {
|
|
if key.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
Text("Aucun horaire")
|
|
} else {
|
|
Text(key.formatted(date: .omitted, time: .shortened))
|
|
.font(.title)
|
|
.fontWeight(.semibold)
|
|
}
|
|
|
|
let names = matches.sorted(by: \.computedOrder)
|
|
.compactMap({ $0.roundTitle() })
|
|
.reduce(into: [String]()) { uniqueNames, name in
|
|
if !uniqueNames.contains(name) {
|
|
uniqueNames.append(name)
|
|
}
|
|
}
|
|
Text(names.joined(separator: ", ")).lineLimit(1).truncationMode(.tail)
|
|
// if matches.count <= matches.first?.courtCount() ?? {
|
|
// } else {
|
|
// Text(matches.count.formatted().appending(" matchs"))
|
|
// }
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
struct CourtOptionsView: View {
|
|
let timeSlots: [Date: [Match]]
|
|
let underlined: Bool
|
|
var allMatches: [Match] {
|
|
timeSlots.flatMap { $0.value }
|
|
}
|
|
|
|
private func _removeCourts() {
|
|
allMatches.forEach { match in
|
|
match.courtIndex = nil
|
|
}
|
|
}
|
|
|
|
private func _eventCourtCount() -> Int { timeSlots.first?.value.first?.currentTournament()?.eventObject()?.eventCourtCount() ?? 2
|
|
}
|
|
|
|
private func _save() {
|
|
let groupByTournaments = allMatches.grouped { match in
|
|
match.currentTournament()
|
|
}
|
|
groupByTournaments.forEach { tournament, matches in
|
|
tournament?.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
}
|
|
}
|
|
|
|
var body: some View {
|
|
Menu {
|
|
Button("Supprimer") {
|
|
_removeCourts()
|
|
_save()
|
|
}
|
|
|
|
Button("Tirer au sort") {
|
|
_removeCourts()
|
|
|
|
let eventCourtCount = _eventCourtCount()
|
|
|
|
for slot in timeSlots {
|
|
var courtsAvailable = Array(0...eventCourtCount)
|
|
let matches = slot.value
|
|
matches.forEach { match in
|
|
if let rand = courtsAvailable.randomElement() {
|
|
match.courtIndex = rand
|
|
courtsAvailable.remove(elements: [rand])
|
|
}
|
|
}
|
|
}
|
|
_save()
|
|
|
|
}
|
|
|
|
Button("Fixer par ordre croissant") {
|
|
_removeCourts()
|
|
|
|
let eventCourtCount = _eventCourtCount()
|
|
|
|
for slot in timeSlots {
|
|
var courtsAvailable = Array(0..<eventCourtCount)
|
|
let matches = slot.value.sorted(by: \.computedOrder)
|
|
for i in 0..<matches.count {
|
|
if !courtsAvailable.isEmpty {
|
|
let court = courtsAvailable.removeFirst()
|
|
matches[i].courtIndex = court
|
|
}
|
|
}
|
|
}
|
|
_save()
|
|
}
|
|
} label: {
|
|
Text("Pistes")
|
|
.underline(underlined)
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
// struct BySlotView: View {
|
|
// @Environment(Tournament.self) var tournament: Tournament
|
|
// let days: [Date]
|
|
// let keys: [Date]
|
|
// let timeSlots: [Date:[Match]]
|
|
// let matches: [Match]
|
|
// let selectedDay: Date?
|
|
// let filterOption: PlanningFilterOption
|
|
// let showFinishedMatches: Bool
|
|
//
|
|
// var body: some View {
|
|
// List {
|
|
// if matches.allSatisfy({ $0.startDate == nil }) == false {
|
|
// ForEach(days.filter({ selectedDay == nil || selectedDay == $0 }), id: \.self) { day in
|
|
// Section {
|
|
// ForEach(keys.filter({ $0.dayInt == day.dayInt }), id: \.self) { key in
|
|
// if let _matches = timeSlots[key]?.sorted(by: filterOption == .byDefault ? \.computedOrder : \.courtIndexForSorting) {
|
|
// DisclosureGroup {
|
|
// ForEach(_matches) { match in
|
|
// NavigationLink {
|
|
// MatchDetailView(match: match)
|
|
// .matchViewStyle(.sectionedStandardStyle)
|
|
//
|
|
// } label: {
|
|
// LabeledContent {
|
|
// if let courtName = match.courtName() {
|
|
// Text(courtName)
|
|
// }
|
|
// } label: {
|
|
// if let groupStage = match.groupStageObject {
|
|
// Text(groupStage.groupStageTitle(.title))
|
|
// } else if let round = match.roundObject {
|
|
// Text(round.roundTitle())
|
|
// }
|
|
// Text(match.matchTitle())
|
|
// }
|
|
// }
|
|
// }
|
|
// } label: {
|
|
// _timeSlotView(key: key, matches: _matches)
|
|
// }
|
|
// }
|
|
// }
|
|
// .onMove(perform: moveSection)
|
|
// } header: {
|
|
// HStack {
|
|
// if day.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
// Text("Sans horaire")
|
|
// } else {
|
|
// Text(day.formatted(.dateTime.day().weekday().month()))
|
|
// }
|
|
// Spacer()
|
|
// let count = _matchesCount(inDayInt: day.dayInt, timeSlots: timeSlots)
|
|
// if showFinishedMatches {
|
|
// Text(self._formattedMatchCount(count))
|
|
// } else {
|
|
// Text(self._formattedMatchCount(count) + " restant\(count.pluralSuffix)")
|
|
// }
|
|
// }
|
|
// } footer: {
|
|
// if day.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
// Text("Il s'agit des matchs qui n'ont pas réussi à être placé par Padel Club. Peut-être à cause de créneaux indisponibles, d'autres tournois ou des réglages.")
|
|
// }
|
|
// }
|
|
// .headerProminence(.increased)
|
|
// }
|
|
// }
|
|
// }
|
|
// }
|
|
//
|
|
// func moveSection(from source: IndexSet, to destination: Int) {
|
|
// let daySlots = keys.filter { selectedDay == nil || $0.dayInt == selectedDay?.dayInt }.sorted()
|
|
//
|
|
// guard let sourceIdx = source.first,
|
|
// sourceIdx < daySlots.count,
|
|
// destination <= daySlots.count else {
|
|
// return
|
|
// }
|
|
//
|
|
// // Create a mutable copy of the time slots for this day
|
|
// var slotsToUpdate = daySlots
|
|
//
|
|
// let updateRange = min(sourceIdx, destination)...max(sourceIdx, destination) - 1
|
|
// print(updateRange)
|
|
//
|
|
// // Perform the move in the array
|
|
// let sourceTime = slotsToUpdate.remove(at: sourceIdx)
|
|
// if sourceIdx < destination {
|
|
// slotsToUpdate.insert(sourceTime, at: destination - 1)
|
|
// } else {
|
|
// slotsToUpdate.insert(sourceTime, at: destination)
|
|
// }
|
|
//
|
|
// // Update matches by swapping their startDates
|
|
// for index in updateRange {
|
|
// // Find the new time slot for these matches
|
|
// let oldStartTime = slotsToUpdate[index]
|
|
// let newStartTime = daySlots[index]
|
|
// guard let matchesToUpdate = timeSlots[oldStartTime] else { continue }
|
|
// print("moving", oldStartTime, "to", newStartTime)
|
|
//
|
|
// // Update each match with the new start time
|
|
// for match in matchesToUpdate {
|
|
// match.startDate = newStartTime
|
|
// }
|
|
// }
|
|
//
|
|
// try? self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
|
|
// }
|
|
//
|
|
//
|
|
// private func _matchesCount(inDayInt dayInt: Int, timeSlots: [Date:[Match]]) -> Int {
|
|
// timeSlots.filter { $0.key.dayInt == dayInt }.flatMap({ $0.value }).count
|
|
// }
|
|
//
|
|
// private func _timeSlotView(key: Date, matches: [Match]) -> some View {
|
|
// LabeledContent {
|
|
// Text(self._formattedMatchCount(matches.count))
|
|
// } label: {
|
|
// if key.monthYearFormatted == Date.distantFuture.monthYearFormatted {
|
|
// Text("Aucun horaire")
|
|
// } else {
|
|
// Text(key.formatted(date: .omitted, time: .shortened)).font(.title).fontWeight(.semibold)
|
|
// }
|
|
// if matches.count <= tournament.courtCount {
|
|
// let names = matches.sorted(by: \.computedOrder)
|
|
// .compactMap({ $0.roundTitle() })
|
|
// .reduce(into: [String]()) { uniqueNames, name in
|
|
// if !uniqueNames.contains(name) {
|
|
// uniqueNames.append(name)
|
|
// }
|
|
// }
|
|
// Text(names.joined(separator: ", ")).lineLimit(1).truncationMode(.tail)
|
|
// } else {
|
|
// Text(matches.count.formatted().appending(" matchs"))
|
|
// }
|
|
// }
|
|
// }
|
|
//
|
|
// fileprivate func _formattedMatchCount(_ count: Int) -> String {
|
|
// return "\(count.formatted()) match\(count.pluralSuffix)"
|
|
// }
|
|
// }
|
|
}
|
|
|
|
enum PlanningFilterOption: Int, CaseIterable, Identifiable {
|
|
var id: Int { self.rawValue }
|
|
|
|
case byDefault
|
|
case byCourt
|
|
|
|
func localizedPlanningLabel() -> String {
|
|
switch self {
|
|
case .byCourt:
|
|
return "Par piste"
|
|
case .byDefault:
|
|
return "Par ordre des matchs"
|
|
}
|
|
}
|
|
}
|
|
|
|
struct FilterOptionKey: EnvironmentKey {
|
|
static let defaultValue: PlanningFilterOption = .byDefault
|
|
}
|
|
|
|
extension EnvironmentValues {
|
|
var filterOption: PlanningFilterOption {
|
|
get { self[FilterOptionKey.self] }
|
|
set { self[FilterOptionKey.self] = newValue }
|
|
}
|
|
}
|
|
|
|
struct ShowFinishedMatchesKey: EnvironmentKey {
|
|
static let defaultValue: Bool = false
|
|
}
|
|
|
|
extension EnvironmentValues {
|
|
var showFinishedMatches: Bool {
|
|
get { self[ShowFinishedMatchesKey.self] }
|
|
set { self[ShowFinishedMatchesKey.self] = newValue }
|
|
}
|
|
}
|
|
|
|
struct EnableMoveKey: EnvironmentKey {
|
|
static let defaultValue: Bool = false
|
|
}
|
|
|
|
extension EnvironmentValues {
|
|
var enableMove: Bool {
|
|
get { self[EnableMoveKey.self] }
|
|
set { self[EnableMoveKey.self] = newValue }
|
|
}
|
|
}
|
|
|