//
//  FeelsApp.swift
//  Shared
//
//  Created by Trey Tartt on 1/5/22.
//

import SwiftUI
import BackgroundTasks
import WidgetKit

@main
struct FeelsApp: App {
    @Environment(\.scenePhase) private var scenePhase
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    let persistenceController = PersistenceController.shared

    init() {
        BGTaskScheduler.shared.cancelAllTaskRequests()
        BGTaskScheduler.shared.register(forTaskWithIdentifier: BGTask.updateDBMissingID, using: nil) { (task) in
            BGTask.runFillInMissingDatesTask(task: task as! BGProcessingTask)
        }
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.viewContext)
        }.onChange(of: scenePhase) { phase in
            if phase == .background {
                BGTask.scheduleBackgroundProcessing()
                WidgetCenter.shared.reloadAllTimelines()
            }
            
            if phase == .active {
                UIApplication.shared.applicationIconBadgeNumber = 0
                persistenceController.fillInMissingDates()
            }
        }
    }
    
}
