//
//  WokaFMVM.swift
//  WOKA
//
//  Created by MacBook Pro on 01/08/24.
//

import UIKit
import AVFoundation

class WokaFMVM{
    
    weak var vc : WokaFMVC!
        
    var player: AVPlayer!
    var playerItem: AVPlayerItem!
    
    var startTimeStamp = Date()
    
    func initView(){
        startTimeStamp = Date()
        vc.mainView.roundCorners(radius: 10, corners: [.topLeft, .topRight])
        let color1 = #colorLiteral(red: 0.5921568627, green: 0.2588235294, blue: 0.8941176471, alpha: 1)
        let color2 = #colorLiteral(red: 0.368627451, green: 0.1215686275, blue: 0.768627451, alpha: 1)
        vc.roundView.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.playBtn.applyGradientBtn(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.playBtn.roundCorner()
        
        setupPlayer()
        vc.addObservers()
        setupAudioSession()
    }
    
    // MARK: - Setup AV & Player

    func setupAudioSession() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            try session.setActive(true)
        } catch {
            print("Failed to set up audio session")
        }
    }
    
    func setupPlayer() {
        guard let data = AuthFunc.shareInstance.staticURLs , let liveFmURL = data.liveFmData?.liveFmURL else{
            AuthFunc.shareInstance.getStaticURLs()
            self.vc.toast(msg: "Issue with radio, please try after sometime.", time: 2)
            return
        }
        
        guard let url = URL(string: liveFmURL) else{return}
//        guard let url = URL(string: "https://a9.asurahosting.com:7530/radio.mp3") else{return}
        playerItem = AVPlayerItem(url: url)
        player = AVPlayer(playerItem: playerItem)
        player.play()
    }
    
    func retryConnect(){
        vc.activityIndicator.startAnimating()
        vc.playBtn.isEnabled = false
        setupPlayer()
        vc.addObservers()
        setupAudioSession()
    }
    
}
