import SwiftUI
import HealthDB
import SFSafeSymbols

private enum TabSelection: Int {
    case databases = 0
    case workouts = 1
    case samples = 2
}

@main
struct HealthImportApp: App {

    @State
    var database = Database()

    @State
    private var selection: TabSelection = .workouts

    @State
    private var databaseList = DatabaseList()

    init() {
        performStartup()
        selection = .workouts
        print("Startup finished, tab: \(selection)")
    }

    private func performStartup() {
        Task {
            databaseList.load()
            DispatchQueue.main.async {
                // Go back to main queue so that list will be updated
                guard let databaseToLoad = databaseList.databases.first(where: { $0.isDefault }) else {
                    return
                }
                Task {
                    print("Loading database \(databaseToLoad.file)")
                    guard database.load(database: databaseToLoad) else {
                        return
                    }
                    DispatchQueue.main.async {
                        self.selection = .workouts
                    }
                }
            }
        }
    }

    var body: some Scene {
        WindowGroup {
            TabView(selection: $selection) {
                WorkoutTab()
                    .environmentObject(database)
                    .tabItem { Label("Workouts", systemSymbol: .figureRun) }
                    .tag(TabSelection.workouts)
                SamplesTab(database: database)
                    .tabItem { Label("Health", systemSymbol: .heartFill) }
                    .tag(TabSelection.samples)
                DatabasesTab(database: database, databases: databaseList)
                    .tabItem {Label("Databases", systemSymbol: .archivebox) }
                    .tag(TabSelection.databases)
            }
            .preferredColorScheme(.dark)
        }
    }
}
