//
//  LeCountdownApp.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 20/01/2023.
//

import SwiftUI
import CoreData
import BackgroundTasks

enum BGTaskIdentifier : String {
    case refresh = "com.staxriver.lecountdown.refresh"
}

@main
struct LeCountdownApp: App {
    
    let persistenceController = PersistenceController.shared

    @State private var tabSelection = 1
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    init() {
        UITabBar.appearance().backgroundColor = UIColor(white: 0.96, alpha: 1.0)
    }
    
    var body: some Scene {
        WindowGroup {
            
            TabView(selection: $tabSelection) {
                ContentView<Countdown>()
                    .environment(\.managedObjectContext, persistenceController.container.viewContext)
                    .environmentObject(Conductor.maestro)
                    .tabItem { Label("Countdown", systemImage: "timer") }
                    .tag(1)
                ContentView<Stopwatch>()
                    .environment(\.managedObjectContext, persistenceController.container.viewContext)
                    .environmentObject(Conductor.maestro)
                    .tabItem { Label("Stopwatch", systemImage: "stopwatch") }
                    .tag(2)
                ContentView<Alarm>()
                    .environment(\.managedObjectContext, persistenceController.container.viewContext)
                    .environmentObject(Conductor.maestro)
                    .tabItem { Label("Alarm", systemImage: "alarm") }
                    .tag(3)
                RecordsView().environment(\.managedObjectContext, persistenceController.container.viewContext)
                    .tabItem { Label("Stats", systemImage: "chart.bar.fill") }
                    .tag(4)
                
            }
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
                self._willEnterForegroundNotification()
            }
            .onAppear {
                self._onAppear()
            }
            .onOpenURL { url in
                print("open URL = \(url)")
                self._performActionIfPossible(url: url)
            }
        }
    }
    
    fileprivate func _willEnterForegroundNotification() {
        Conductor.maestro.cleanup()
    }
    
    fileprivate func _onAppear() {
        self._registerBackgroundRefreshes()
        
//        Task {
//            for s in Sound.allCases {
//                do {
//                    let d = try await s.duration()
//                    print("\(s) duration = \(d)")
//                } catch {
//                    print("error = \(error)")
//                }
//            }
//        }
    }
    
    fileprivate func _registerBackgroundRefreshes() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: BGTaskIdentifier.refresh.rawValue, using: nil) { task in
             self._handleAppRefresh(task: task as! BGAppRefreshTask)
        }
    }
    
    fileprivate func _handleAppRefresh(task: BGAppRefreshTask) {
        
        print("_handleAppRefresh = \(task.description)")
        
        task.expirationHandler = {
            print("expired")
        }
        
        DispatchQueue.main.async {
            Conductor.maestro.updateLiveActivities()
            task.setTaskCompleted(success: true)
        }
        
    }
    
    fileprivate func _performActionIfPossible(url: URL) {
        
        let context = persistenceController.container.viewContext
        let urlString = url.absoluteString
        if let timer = context.object(stringId: urlString) as? AbstractTimer {
            
            switch timer {
            case is Countdown:
                tabSelection = 1
            case is Stopwatch:
                tabSelection = 2
            case is Alarm:
                tabSelection = 3
            default:
                print("url not managed, object is \(timer)")
                break
            }
        } else {
            print("url not managed: \(url)")
        }
        
    }
    
}
