//
//  AppDelegate.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 24/01/2023.
//

import Foundation
import UIKit

class AppDelegate : NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        UNUserNotificationCenter.current().delegate = self
        Conductor.maestro.cleanupCountdowns()
        return true
    }
    
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {

        print("didReceive notification")
        let timerId = self._timerId(notificationId: response.notification.request.identifier)
        Conductor.maestro.cancelCountdown(id: timerId)
        
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent notification")
//        completionHandler([.banner])
        
        let timerId = self._timerId(notificationId: notification.request.identifier)
        Conductor.maestro.notifyUser(countdownId: timerId)
    }
    
    fileprivate func _timerId(notificationId: String) -> String {
        let components = notificationId.components(separatedBy: CountdownScheduler.notificationIdSeparator)
        if components.count == 2 {
            return components[0]
        } else {
            fatalError("bad notification format : \(notificationId)")
        }

    }
    
    
}
