import Foundation

/// Persists app state (last playlist, last track, playback position) to UserDefaults.
struct AppState {
    private static let defaults = UserDefaults.standard

    private static let keyLastPlaylistID = "appState.lastPlaylistID"
    private static let keyLastEntryID = "appState.lastEntryID"
    private static let keyLastTrackFilePath = "appState.lastTrackFilePath"
    private static let keyLastPlaybackTime = "appState.lastPlaybackTime"

    // MARK: - Save

    static func saveLastPlaylist(id: UUID) {
        defaults.set(id.uuidString, forKey: keyLastPlaylistID)
    }

    static func saveLastEntry(id: UUID) {
        defaults.set(id.uuidString, forKey: keyLastEntryID)
    }

    static func saveLastTrack(filePath: String) {
        defaults.set(filePath, forKey: keyLastTrackFilePath)
    }

    static func savePlaybackTime(_ time: TimeInterval) {
        defaults.set(time, forKey: keyLastPlaybackTime)
    }

    static func savePlaybackState(
        playlistID: UUID?,
        entryID: UUID?,
        trackFilePath: String?,
        playbackTime: TimeInterval
    ) {
        if let id = playlistID { saveLastPlaylist(id: id) }
        if let id = entryID { saveLastEntry(id: id) }
        if let path = trackFilePath { saveLastTrack(filePath: path) }
        savePlaybackTime(playbackTime)
    }

    // MARK: - Load

    static var lastPlaylistID: UUID? {
        defaults.string(forKey: keyLastPlaylistID).flatMap { UUID(uuidString: $0) }
    }

    static var lastEntryID: UUID? {
        defaults.string(forKey: keyLastEntryID).flatMap { UUID(uuidString: $0) }
    }

    static var lastTrackFilePath: String? {
        defaults.string(forKey: keyLastTrackFilePath)
    }

    static var lastPlaybackTime: TimeInterval {
        defaults.double(forKey: keyLastPlaybackTime)
    }
}
