import Foundation
import ActivityKit

/// Tiny facade around ActivityKit so TrackingView doesn't have to know the
/// details. There is at most one walk activity alive at any time.
@MainActor
enum WalkActivityController {
    private static var current: Activity<WalkActivityAttributes>?

    static func start(startedAt: Date, initialState: WalkActivityAttributes.WalkActivityState) {
        guard ActivityAuthorizationInfo().areActivitiesEnabled else { return }
        // Kill anything left over from a previous (orphaned) session.
        if current != nil { end() }
        let attributes = WalkActivityAttributes(startedAt: startedAt)
        let content = ActivityContent(state: initialState, staleDate: nil)
        do {
            current = try Activity.request(
                attributes: attributes,
                content: content,
                pushType: nil
            )
        } catch {
            print("Live Activity request failed: \(error)")
        }
    }

    static func update(_ state: WalkActivityAttributes.WalkActivityState) {
        let activity = current
        Task { @MainActor in
            await activity?.update(ActivityContent(state: state, staleDate: nil))
        }
    }

    static func end() {
        let activity = current
        current = nil
        Task { @MainActor in
            await activity?.end(nil, dismissalPolicy: .immediate)
        }
    }
}
