//
//  TimerRouter.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 02/02/2023.
//

import Foundation
import NotificationCenter

class TimerRouter {
    
    static func performAction(timer: AbstractTimer, handler: @escaping (Result<Bool, Error>) -> Void) {
        switch timer {
        case let countdown as Countdown:
            self._launchCountdown(countdown, handler: handler)
        case let alarm as Alarm:
            self._scheduleAlarm(alarm, handler: handler)
        case let stopwatch as Stopwatch:
            self._startStopwatch(stopwatch, handler: handler)
        default:
            print("missing launcher for \(self)")
        }
        
    }
    
    static func stopTimer(timer: AbstractTimer) {
        switch timer {
        case let countdown as Countdown:
            Conductor.maestro.cancelCountdown(id: countdown.stringId)
        case let stopwatch as Stopwatch:
            self._stopStopwatch(stopwatch)
        default:
            print("missing launcher for \(self)")
        }
    }
    
    fileprivate static func _launchCountdown(_ countdown: Countdown, handler: @escaping (Result<Bool, Error>) -> Void) {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            
            switch settings.authorizationStatus {
            case .notDetermined, .denied:
                handler(.failure(TimerError.notificationAuthorizationMissing))
            default:
                CountdownScheduler.master.scheduleIfPossible(countdown: countdown) { result in
                    switch result {
                    case .success(_):
                        handler(.success(true))
                    case .failure(let failure):
                        handler(.failure(failure))
                    }
                }
            }
        }

    }
    
    fileprivate static func _scheduleAlarm(_ alarm: Alarm, handler: @escaping (Result<Bool, Error>) -> Void) {
        
    }
    
    fileprivate static func _startStopwatch(_ stopwatch: Stopwatch, handler: @escaping (Result<Bool, Error>) -> Void) {
        Conductor.maestro.startStopwatch(stopwatch)
    }
    
    fileprivate static func _stopStopwatch(_ stopwatch: Stopwatch, end: Date? = nil) {
        Conductor.maestro.stopStopwatch(stopwatch)
    }
    
}
