//
//  BridgeModule+Timer.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/21/24.
//

import Foundation

extension BridgeModule {
    func startWorkoutTimer() {
        currentWorkoutRunTimer?.invalidate()
        currentWorkoutRunTimer = nil
        currentWorkoutRunTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
            self.currentWorkoutRunTimeInSeconds += 1
            self.sendCurrentExerciseToWatch()
        })
        currentWorkoutRunTimer?.fire()
    }
    
    func startExerciseTimerWith(duration: Int) {
        DispatchQueue.main.async {
            self.currentExerciseTimer?.invalidate()
            self.currentExerciseTimer = nil
            self.currentExerciseTimeLeft = duration
            self.currentExerciseTimer = Timer.scheduledTimer(timeInterval: 1,
                                                             target: self,
                                                             selector: #selector(self.updateCurrentExerciseTimer),
                                                             userInfo: nil,
                                                             repeats: true)
            self.currentExerciseTimer?.fire()
        }
    }
    
    @objc func updateCurrentExerciseTimer() {
        if currentExerciseTimeLeft > 1 {
            currentExerciseTimeLeft -= 1
            
            if let currentExercise = currentExerciseInfo.allSupersetExecercise, let audioQueues = currentExercise.audioQueues {
                if let audioQueue = audioQueues.first(where: {
                    $0.playAt == currentExerciseTimeLeft
                }) {
                    switch audioQueue.audioType {
                        
                    case .shortBeep:
                        AudioEngine.shared.playBeep()
                    case .finishBeep:
                        AudioEngine.shared.playFinished()
                    case .remoteURL(let url):
                        AudioEngine.shared.playRemoteAudio(fromURL: url)
                    }
                }
            }
        } else {
            nextExercise()
        }
    }
}
