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

import UIKit
import AVFoundation
import GoogleMobileAds
import MediaPlayer

class WokaFMVM{
    
    weak var vc : WokaFMVC!
        
    var player: AVPlayer!
    var playerItem: AVPlayerItem!
    
    var startTimeStamp = Date()
    var bottomBannerView = GADBannerView()
    
    // if retry count is 4 reset it to 0
    var retryCount = 0
    
    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()
        
        vc.mainView.roundCorners(radius: 10, corners: [.topLeft, . topRight])
        
        setupPlayer()
        vc.addObservers()
        setupAudioSession()
        
        vc.blackView.addTapGesture { [weak self] in
            guard let self else{return}
            PersistentStorage.shared.addRadioCount()
            if let postID = AuthFunc.shareInstance.staticURLs?.liveFmData?.id {
                let duration = DateFormatterLib.dateDifferenceINT(date1: self.startTimeStamp, date2: Date())
                AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.FM.rawValue, duration: duration, catID: 0) { _ in}
            }
            self.vc.dismiss(animated: true)
        }
        setGoogleAd()
        
        
//        updateNowPlayingInfo()
    }
    
    // MARK: - SetupAd
    
    func stopMPNowPlayin(){
        MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
    }
    
    func setupNowPlayingInfo() {
        let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
        var nowPlayingInfo: [String: Any] = [:]

        // Set the media title, artist, and album name
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Live FM"
        nowPlayingInfo[MPMediaItemPropertyArtist] = "WOKA"
        nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = "Album Name"
        
        // Optional: Set the artwork
        if let artworkImage = UIImage(named: "WokaLogo") {
            let artwork = MPMediaItemArtwork(boundsSize: artworkImage.size) { size in
                return artworkImage
            }
            nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
        }

        // Set the duration and current playback position
        if let currentItem = player.currentItem {
            nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = currentItem.asset.duration.seconds
            nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
        }
        
        // Assign the nowPlayingInfo to the center
        nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
    }

    func setupRemoteCommandCenter() {
        let commandCenter = MPRemoteCommandCenter.shared()

        // Enable play command
        commandCenter.playCommand.addTarget { [unowned self] event in
            if player.rate == 0.0 {
                player.play()
                return .success
            }
            return .commandFailed
        }

        // Enable pause command
        commandCenter.pauseCommand.addTarget { [unowned self] event in
            if player.rate == 1.0 {
                player.pause()
                return .success
            }
            return .commandFailed
        }

        // Enable next and previous track commands if needed
        commandCenter.nextTrackCommand.isEnabled = false
        commandCenter.previousTrackCommand.isEnabled = false
    }
    
    func updateNowPlayingInfo() {
        if let currentItem = player.currentItem {
            var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
            nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
            MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
        }
    }


    
    func setGoogleAd(){
        /*
         Show google ads with dispatch queue.
         */
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: { [weak self] in
            guard let self else{return}
            AdReusable.sharedInstance.setupBannerAd(bannerView: self.bottomBannerView, in: vc.adView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self.vc)
//            vc.adView.isHidden = false
        })
    }

    // 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()
//        setGoogleAd()
    }
    
    func retryConnect(){
        vc.activityIndicator.startAnimating()
        vc.playBtn.isEnabled = false
        setupPlayer()
        vc.addObservers()
        setupAudioSession()
    }
    
}
