//
//  AudioPlayerManager.swift
//  WoWonder
//
//  Created by iMac on 18/08/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import Foundation
import AVFoundation

protocol AudioPlayerDelegate {
    func playbackStateChanged(at indexPath: IndexPath?)
}

class AudioPlayerHelper: NSObject {
    
    static let shared = AudioPlayerHelper()
    
    var audioPlayer: AVAudioPlayer?
    var playingIndexPath: IndexPath?
    var oldIndexPath: IndexPath?
    var delegate: AudioPlayerDelegate?
    
    func playAudio(at indexPath: IndexPath, url: URL) {
        if indexPath == self.playingIndexPath {
            if let player = self.audioPlayer, player.isPlaying {
                player.pause()
                self.delegate?.playbackStateChanged(at: self.playingIndexPath)
            } else {
                self.audioPlayer?.play()
                self.delegate?.playbackStateChanged(at: self.playingIndexPath)
            }
        } else {
            self.stopAudio()
            do {
                let audioSession = AVAudioSession.sharedInstance()
                try audioSession.setCategory(.playback)
                try audioSession.setActive(true)
                let soundData = try Data(contentsOf: url)
                self.audioPlayer = try AVAudioPlayer(data: soundData)
                self.audioPlayer?.delegate = self
                self.audioPlayer?.prepareToPlay()
                self.audioPlayer?.play()
                self.oldIndexPath = nil
                self.playingIndexPath = indexPath
                self.delegate?.playbackStateChanged(at: self.playingIndexPath)
            } catch {
                print("Error playing audio: \(error)")
            }
        }
    }
    
    func stopAudio() {
        self.audioPlayer?.stop()
        self.oldIndexPath = playingIndexPath
        self.playingIndexPath = nil
        self.audioPlayer = nil
        self.delegate?.playbackStateChanged(at: self.oldIndexPath)
    }
    
    func stopAudioPlayer() {
        self.audioPlayer?.stop()
        self.oldIndexPath = nil
        self.playingIndexPath = nil
        self.audioPlayer = nil
    }
    
}

extension AudioPlayerHelper: AVAudioPlayerDelegate {
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.stopAudio()
    }
    
}

