//
//  CreatorCommunityMediaPlayerManager.swift
//  SodaLive
//
//  Created by klaus on 8/7/24.
//

import Foundation
import AVKit
import MediaPlayer

final class CreatorCommunityMediaPlayerManager: NSObject, ObservableObject {
    static let shared = CreatorCommunityMediaPlayerManager()
    
    @Published private (set) var currentPlayingContentId: Int = 0
    @Published private (set) var isPlaying = false
    
    @Published var isLoading = false
    @Published var errorMessage = ""
    @Published var isShowPopup = false
    
    private var player: AVAudioPlayer!
    
    private func playContent(item: CreatorCommunityContentItem) {
        if item.contentId <= 0 {
            return
        }
        
        if (currentPlayingContentId == item.contentId && !isPlaying) {
            resumeContent()
            return
        }
        
        stopContent()
        currentPlayingContentId = item.contentId
        
        guard let url = URL(string: item.url) else {
            showError()
            return
        }
        
        isLoading = true
        URLSession.shared.dataTask(with: url) { [unowned self] data, response, error in
            guard let audioData = data else {
                self.isLoading = false
                return
            }
            
            do {
                let audioSession = AVAudioSession.sharedInstance()
                try audioSession.setCategory(.playback, mode: .moviePlayback)
                try audioSession.setActive(true)
                
                self.player = try AVAudioPlayer(data: audioData)
                
                DispatchQueue.main.async {
                    self.player?.volume = 1
                    self.player?.delegate = self
                    self.player?.prepareToPlay()
                    
                    self.player?.play()
                    self.isPlaying = self.player.isPlaying
                }
            } catch {
                DispatchQueue.main.async {
                    self.showError()
                }
            }
            
            DispatchQueue.main.async {
                self.isLoading = false
            }
        }.resume()
    }
    
    private func resumeContent() {
        if let player = player {
            player.play()
            isPlaying = player.isPlaying
        }
    }
    
    private func showError() {
        self.errorMessage = "오류가 발생했습니다. 다시 시도해 주세요."
        self.isShowPopup = true
    }
}

extension CreatorCommunityMediaPlayerManager {
    func toggleContent(item: CreatorCommunityContentItem) {
        if currentPlayingContentId == item.contentId {
            if let player = player, player.isPlaying {
                pauseContent()
            } else {
                resumeContent()
            }
        } else {
            playContent(item: item)
        }
    }
    
    func pauseContent() {
        if let player = player {
            player.pause()
            isPlaying = player.isPlaying
        }
    }
    
    func stopContent() {
        if let player = player {
            player.stop()
            player.currentTime = 0
        }
        
        isPlaying = false
        currentPlayingContentId = 0
    }
}

extension CreatorCommunityMediaPlayerManager: AVAudioPlayerDelegate {
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        stopContent()
    }
}


struct CreatorCommunityContentItem {
    let contentId: Int
    let url: String
}
