//
//  PadelClubApp.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 02/02/2024.
//

import SwiftUI
import LeStorage
import TipKit
import FirebaseCore

@main
struct PadelClubApp: App {
    let persistenceController = PersistenceController.shared
    @State private var navigationViewModel = NavigationViewModel()
    @StateObject var networkMonitor: NetworkMonitor = NetworkMonitor()
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
    static var appVersion: String {
        let dictionary = Bundle.main.infoDictionary!
        let version = dictionary["CFBundleShortVersionString"] as! String
        let build = dictionary["CFBundleVersion"] as! String
        return "\(version) (\(build))"
    }

    var body: some Scene {
        WindowGroup {
            MainView()
                .environmentObject(networkMonitor)
                .environment(navigationViewModel)
                .accentColor(.master)
                .onAppear {
                    networkMonitor.checkConnection()
                    self._onAppear()
                }
                .task {
                    
                    //try? Tips.resetDatastore()

                    try? Tips.configure([
                        .displayFrequency(.immediate),
                        .datastoreLocation(.applicationDefault)
                    ])
                }
                .environment(\.managedObjectContext, persistenceController.localContainer.viewContext)
        }
    }
    
    fileprivate func _onAppear() {
        let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        Logger.log("doc dir = \(docURL.absoluteString)")
        UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}
