//
//  Countdown+Extension.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 25/01/2023.
//

import Foundation
import SwiftUI
import CoreData

enum TimerError: Error {
    case notificationAuthorizationMissing
}

extension AbstractTimer {
    
    var displayName: String {
        return self.name ?? self.coolpic.emoji
    }
    
    var name: String? {
        return self.activity?.name
    }
    
    var url: URL {
        if let url = URL(string: self.stringId) {
            return url
        } else {
            fatalError("Can't produce url with \(self.stringId)")
        }
    }
    
    var coolpic: CoolPic {
        if let image, let coolpic = CoolPic(rawValue: image) {
            return coolpic
        }
        return CoolPic.allCases[0]
    }
    
    var imageName: String {
        return self.coolpic.rawValue
    }
    
}

extension AbstractSoundTimer {
    
    var coolSound: Sound {
        return Sound.allCases[Int(self.sound)]
    }
    
    var soundName: String {
        coolSound.soundName
    }
    
}

extension Countdown {
    
    static func fake(context: NSManagedObjectContext) -> Countdown {
        let cd = Countdown(context: context)
        cd.duration = 4 * 60.0
        let activity = Activity(context: context)
        activity.name = "Tea"
        cd.activity = activity
        return cd
    }
    
}

extension Alarm {
    
    static func fake(context: NSManagedObjectContext) -> Alarm {
        let alarm = Alarm(context: context)
        alarm.fireDate = Date()
        let activity = Activity(context: context)
        activity.name = "Wakeup"
        alarm.activity = activity
        return alarm
    }

}

extension Stopwatch {
    
    static func fake(context: NSManagedObjectContext) -> Stopwatch {
        let stopwatch = Stopwatch(context: context)
        let activity = Activity(context: context)
        activity.name = "Run"
        stopwatch.activity = activity
        return stopwatch
    }

}

extension Record {
    
    var details: String {
        if let start, let end {
            return "\(start) - \(end)"
        } else {
            return "no details"
        }
    }
    
}

extension Activity {
    
    fileprivate static var formatter: NumberFormatter = NumberFormatter()
    
    var recordCount: String {
        let count: Int = self.records?.count ?? 0
        return Activity.formatter.string(from: NSNumber(value: count)) ?? "--"
    }
    
}
