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

import Intents

class IntentHandler: INExtension, SelectCountdownIntentHandling {
    
    func resolveCountdown(for intent: SelectCountdownIntent) async -> [CountdownPropertiesResolutionResult] {
        print("***resolveCountdown")
        if let properties = intent.countdown?.first {
            return [CountdownPropertiesResolutionResult.success(with: properties)]
        }
        return [CountdownPropertiesResolutionResult.needsValue()]

    }
    
    func provideCountdownOptionsCollection(for intent: SelectCountdownIntent) async throws -> INObjectCollection<CountdownProperties> {
        print("*** provideCountdownOptionsCollection")

        do {
            let countdowns = try IntentDataProvider.main.countdowns()
            
            let properties: [CountdownProperties] = countdowns.map { countdown in

                let displayName: String
                let formattedDuration = countdown.duration.minuteSecond
                if let name = countdown.activity?.name, !name.isEmpty {
                    displayName = "\(name) (\(formattedDuration))"
                } else {
                    displayName = formattedDuration
                }
    
                let cp = CountdownProperties(identifier: countdown.objectID.uriRepresentation().absoluteString, display: displayName)
                return cp
            }
            
            let collection: INObjectCollection<CountdownProperties> = INObjectCollection(items: properties)
            print("*** provide \(properties.count) countdowns")

            return collection
        } catch {
            print("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
    }
    
}
