//
//  Sound.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 30/01/2023.
//

import Foundation
import AVFoundation

// Sound id are stored thus case order should not be changed
enum Sound : Int, CaseIterable, Identifiable {
    
    var id: Int { return self.rawValue }
    
    case trainhorn // default
    case forestStream
    
    var localizedString: String {
        switch self {
        case .trainhorn: return NSLocalizedString("Train horn", comment: "")
        case .forestStream: return NSLocalizedString("Forest stream", comment: "")
        }
    }
    
    var soundName: String {
        switch self {
        case .trainhorn: return "train_horn.mp3"
        case .forestStream: return "forest_stream.mp3"
        }
    }
    
    var duration: TimeInterval {
        switch self {
        case .trainhorn: return 7.8
        case .forestStream: return 300.1
        }
    }
    
    var url: URL? {
        
        let components = self.soundName.components(separatedBy: ".")
        if components.count == 2 {
            return Bundle.main.url(forResource: components[0], withExtension: components[1])
        } else {
            print("bad sound file name for \(self)")
            return nil
        }
        
    }
    
    func soundFile() throws -> SoundFile {
        return try SoundFile(fullName: self.soundName)
    }
    
    func duration() async throws -> TimeInterval {
        
        guard let url = self.url else {
            print("sound \(self) has no url")
            return -1.0
        }
        
        let audioAsset = AVURLAsset.init(url: url, options: nil)
        let duration = try await audioAsset.load(.duration)
        return CMTimeGetSeconds(duration)
    }
    
}
