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/Views/Navigation/MainView.swift

203 lines
7.4 KiB

//
// MainView.swift
// PadelClub
//
// Created by Razmig Sarkissian on 29/02/2024.
//
import SwiftUI
import LeStorage
struct MainView: View {
@EnvironmentObject var dataStore: DataStore
@AppStorage("importingFiles") var importingFiles: Bool = false
@Environment(NavigationViewModel.self) private var navigation: NavigationViewModel
@State private var checkingFilesAttempt: Int = 0
@State private var checkingFiles: Bool = false
@State private var mainViewId: UUID = UUID()
var lastDataSource: String? {
dataStore.appSettings.lastDataSource
}
var selectedTabHandler: Binding<TabDestination?> { Binding(
get: { navigation.selectedTab },
set: {
if $0 == navigation.selectedTab {
// switch navigation.selectedTab {
// case .activity:
// navigation.path.removeLast()
// case .toolbox:
// navigation.toolboxPath = NavigationPath()
// case .umpire:
// navigation.umpirePath = NavigationPath()
// case .ongoing:
// navigation.ongoingPath = NavigationPath()
// case .tournamentOrganizer:
// break
// case .none:
// break
// }
} else {
navigation.selectedTab = $0
}
}
)}
private func _isConnected() -> Bool {
return StoreCenter.main.hasToken() && StoreCenter.main.userId != nil
}
var badgeText: Text? {
return (dataStore.appSettings.didCreateAccount && _isConnected() == false) ? Text("!").font(.headline) : nil
}
var body: some View {
TabView(selection: selectedTabHandler) {
ActivityView()
.tabItem(for: .activity)
.onAppear {
if lastDataSource == nil, checkingFiles == false, importingFiles == false {
Task {
await self._checkSourceFileAvailability()
}
} else if let lastDataSource, lastDataSource != URL.importDateFormatter.string(from: Date()), checkingFiles == false, importingFiles == false {
Task {
await self._checkSourceFileAvailability()
}
}
}
.toolbarBackground(.visible, for: .tabBar)
TournamentOrganizerView()
.tabItem(for: .tournamentOrganizer)
.toolbarBackground(.visible, for: .tabBar)
OngoingView()
.tabItem(for: .ongoing)
.badge(self.dataStore.runningMatches().count)
.toolbarBackground(.visible, for: .tabBar)
ToolboxView()
.tabItem(for: .toolbox)
.toolbarBackground(.visible, for: .tabBar)
UmpireView()
.tabItem(for: .umpire)
.badge(badgeText)
.toolbarBackground(.visible, for: .tabBar)
// PadelClubView()
// .tabItem(for: .padelClub)
}
.id(mainViewId)
.onChange(of: dataStore.user.id) {
if StoreCenter.main.userId == nil { // user disconnected
navigation.path.removeLast(navigation.path.count)
mainViewId = UUID()
}
}
.environmentObject(dataStore)
.task {
//await self._checkSourceFileAvailability()
if StoreCenter.main.hasToken() {
do {
try await dataStore.clubs.loadDataFromServerIfAllowed()
} catch {
Logger.error(error)
}
let ids = dataStore.user.clubs
var save = false
ids.forEach { clubId in
if dataStore.clubs.findById(clubId) == nil {
dataStore.user.clubs.removeAll(where: { $0 == clubId })
save = true
}
}
if save {
dataStore.saveUser()
}
}
}
// .refreshable {
// Task {
// await self._checkSourceFileAvailability()
// }
// }
.overlay(alignment: .bottom) {
if importingFiles {
_activityStatusBoxView()
} else {
_activityStatusBoxView()
.deferredRendering(for: .seconds(3))
}
}
}
func _activityStatusBoxView() -> some View {
return _activityStatus()
.toastFormatted()
}
@ViewBuilder
func _activityStatus() -> some View {
if importingFiles {
HStack(spacing: 20) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: Color.black))
if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable {
if mostRecentDateAvailable > SourceFileManager.shared.lastDataSourceDate() ?? .distantPast {
Text("import " + mostRecentDateAvailable.monthYearFormatted)
}
}
}
} else if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable, let lastDataSourceDate = SourceFileManager.shared.lastDataSourceDate() {
if mostRecentDateAvailable > lastDataSourceDate {
Label(mostRecentDateAvailable.monthYearFormatted + " disponible", systemImage: "exclamationmark.triangle")
.labelStyle(.titleAndIcon)
} else {
Label(mostRecentDateAvailable.monthYearFormatted, systemImage: "checkmark")
.labelStyle(.titleAndIcon)
}
}
}
private func _checkSourceFileAvailability() async {
print("dataStore.appSettings.lastDataSource :", dataStore.appSettings.lastDataSource ?? "none")
print("check internet")
print("check files on internet")
print("check if any files on internet are more recent than here")
checkingFiles = true
await SourceFileManager.shared.fetchData()
checkingFilesAttempt += 1
checkingFiles = false
if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable, mostRecentDateAvailable > SourceFileManager.shared.lastDataSourceDate() ?? .distantPast {
_startImporting()
}
}
private func _startImporting() {
importingFiles = true
Task {
let lastDataSource = await FileImportManager.shared.importDataFromFFT()
await MainActor.run {
importingFiles = false
}
dataStore.appSettings.lastDataSource = lastDataSource
dataStore.appSettingsStorage.write()
if let lastDataSource, let mostRecentDate = URL.importDateFormatter.date(from: lastDataSource) {
await MonthData.calculateCurrentUnrankedValues(mostRecentDateAvailable: mostRecentDate)
}
await _downloadPreviousDate()
}
}
private func _downloadPreviousDate() async {
await SourceFileManager.shared.getAllFiles(initialDate: "05-2024")
}
}
//#Preview {
// MainView()
//}