//
//  LiveAppleApp.swift
//  LiveApple
//
//  Created by Shadowfacts on 9/24/22.
//

import SwiftUI
import BackgroundTasks

@main
struct LiveAppleApp: App {
    @UIApplicationDelegateAdaptor private var delegate: AppDelegate
    @State var controller: PlayerController!
    
    var body: some Scene {
        WindowGroup {
            ContentView(controller: controller)
                .task {
                    controller = PlayerController()
                    delegate.controller = controller
                    await controller.start()
                }
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    var controller: PlayerController!
    
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // can't update in the background without going through BackgroundTasks
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "task", using: .main) { [unowned self] task in
            Task {
                await BackgroundManager(controller: self.controller).run()
                task.setTaskCompleted(success: true)
            }
        }
        
//        application.beginReceivingRemoteControlEvents()
        
        return true
    }
}
