//
//  JustOneThingProvider.swift
//  JustOneThing
//
//  Created by Alan Francis on 24/06/2023.
//

import WidgetKit
import SwiftUI
import Intents

class ThingCoreDataStore {
    let managedObjectContext = PersistenceController.shared.viewContext
    
    public var things:[Thing] {
        do {
            return try managedObjectContext.fetch(PersistentThing.request).map { persistentThing in
                persistentThing.asThing
            }
        }
        catch {
            return []
        }
    }
    
    public var shuffledThings:[Thing] {
        return self.things.shuffled()
    }
}

struct ThingDataStore {
    public var things:[Thing] = [
        Thing(text: "Eat", createdAt: Date()),
        Thing(text: "Dont forget to pack your toothbrush", createdAt: Date()),
        Thing(text: "Buy Toothpaste", createdAt: Date()),
        Thing(text: "Passport", createdAt: Date()),
        Thing(text: "Cables", createdAt: Date()),
        Thing(text: "Get some dollars", createdAt: Date()),
    ]
    
    public var shuffledThings:[Thing] {
        things.shuffled()
    }
}

extension Date {
    mutating public func withAddedMinutes(_ minutes:Double) -> Date {
        self.addTimeInterval(minutes*60)
        return self
    }
}

struct ThingProvider: IntentTimelineProvider {
    var thingStore = ThingCoreDataStore()
    
    func placeholder(in context: Context) -> ThingEntry {
        ThingEntry(thing: .placeholder)
    }

    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (ThingEntry) -> ()) {
        completion(ThingEntry(thing: .placeholder, config: configuration))
    }

    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<ThingEntry>) -> ()) {
        var timestamp = Date.now
        let entries = thingStore.shuffledThings.map {
            ThingEntry(thing: $0,
                       timelineDate: timestamp.withAddedMinutes(15),
                       config: configuration)
        }
        completion(Timeline(entries: entries, policy: .atEnd))
    }
}

extension ThingProvider {
    func recommendations() -> [IntentRecommendation<ConfigurationIntent>] {
        return [
            IntentRecommendation(intent: ConfigurationIntent(), description: "My Intent Widget")
        ]
    }
}


struct ThingEntry: TimelineEntry {
    let date: Date
    let configuration: ConfigurationIntent
    let thing: Thing
    
    public init(thing:Thing, timelineDate:Date = .now, config:ConfigurationIntent = ConfigurationIntent()) {
        self.thing = thing
        self.date = timelineDate
        self.configuration = config
    }
}
