//
//  LaunchTimer.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 07/03/2023.
//

import Foundation
import AppIntents
import SwiftUI

@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
struct StartTimerIntent: AppIntent, CustomIntentMigratedAppIntent {
    
    static let intentClassName = "StartTimerIntent"
    static var title: LocalizedStringResource = "Launch Timer"
    static var description = IntentDescription("Launch timers and stopwatches")

    @Parameter(title: "Timer")
    var timer: TimerIdentifierAppEntity?

    static var parameterSummary: some ParameterSummary {
        Summary()
    }

    func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView {
        
        let timerIdentifier: TimerIdentifierAppEntity
        if let timer {
            timerIdentifier = timer
        } else {
            timerIdentifier = try await $timer.requestDisambiguation(among: timerEntities())
        }
                
        if let abstractTimer = IntentDataProvider.main.timer(id: timerIdentifier.id) {
            do {
                let _ = try await TimerRouter.performAction(timer: abstractTimer)
                print("perform() success !")
                return .result(dialog: "Timer \(abstractTimer.displayName) started")
            } catch {
                Logger.error(error)
                let dialog: IntentDialog = "\(error.localizedDescription)"
                return .result(dialog: dialog)
            }
        }
        return .result(dialog: "The timer has not been found in the app")
    }
    
    func timerEntities() -> [TimerIdentifierAppEntity] {
        do {
            let timers: [AbstractTimer] = try IntentDataProvider.main.timers()
            return timers.map { TimerIdentifierAppEntity(id: $0.stringId, displayString: $0.displayName) }
        } catch {
            return []
        }
    }
    
}
