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

import Foundation
import BackgroundTasks
import Combine
import CoreLocation
import MediaPlayer

@MainActor
class BackgroundManager: NSObject {
    private var cancellables = Set<AnyCancellable>()
    private var continuation: CheckedContinuation<Void, Never>!
    private var manager = CLLocationManager()
    
    init(controller: PlayerController) {
        super.init()
        
        print("running in the background!")
        controller.$currentFrame
            .sink { [unowned self] newFrame in
                Task {
                    if let newFrame {
                        await controller.activity?.update(using: BadAppleAttributes.ContentState(frame: newFrame))
//                        print("updated!")
                    } else {
                        self.continuation.resume()
                    }
                }
            }
            .store(in: &cancellables)
        
        // tracking the location lets us stay alive in the background
        manager.delegate = self
        manager.requestAlwaysAuthorization()
        manager.allowsBackgroundLocationUpdates = true
        manager.startUpdatingLocation()
    }
    
    func run() async {
        await withCheckedContinuation { continuation in
            self.continuation = continuation
        }
    }
}

extension BackgroundManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("location: \(locations.last!)")
    }
}
