//
//  IntentHandler.swift
//  LaunchIntents
//
//  Created by Laurent Morvillier on 25/01/2023.
//

import Intents

class IntentHandler: INExtension, SelectTimerIntentHandling {
    
    func resolveTimer(for intent: SelectTimerIntent) async -> [TimerPropertiesResolutionResult] {
        print("***resolveCountdown")
        if let properties = intent.timer?.first {
            return [TimerPropertiesResolutionResult.success(with: properties)]
        }
        return [TimerPropertiesResolutionResult.needsValue()]

    }
    
    func provideTimerOptionsCollection(for intent: SelectTimerIntent) async throws -> INObjectCollection<TimerProperties> {
        print("*** provideCountdownOptionsCollection")

        do {
            let timers = try IntentDataProvider.main.timers()
            
            let properties: [TimerProperties] = timers.map { timer in

                let displayName: String
                switch timer {
                case let countdown as Countdown:
                    let formattedDuration = countdown.duration.minuteSecond
                    if let name = timer.activity?.name, !name.isEmpty {
                        displayName = "\(name) (\(formattedDuration))"
                    } else {
                        displayName = formattedDuration
                    }
                    break
                case let stopwatch as Stopwatch:
                    displayName = stopwatch.activity?.name ?? "no name"
                default:
                    displayName = "no name"
                }
    
                let cp = TimerProperties(identifier: timer.objectID.uriRepresentation().absoluteString, display: displayName)
                return cp
            }
            
            let collection: INObjectCollection<TimerProperties> = INObjectCollection(items: properties)
            print("*** provide \(properties.count) countdowns")

            return collection
        } catch {
            Logger.error(error)
            throw error
//            completion(nil, error)
        }
    }
    
    
    override func handler(for intent: INIntent) -> Any {
        // This is the default implementation.  If you want different objects to handle different intents,
        // you can override this and return the handler you want for that particular intent.
        
        return self
    }
    
}
