//
//  ThemeTwoVC.swift
//  WOKA
//
//  Created by Bilal on 24/05/2024.
//

import UIKit
import AVFAudio
import AVFoundation
import GoogleMobileAds

class ThemeTwoVC: UIViewController{
    
    weak var delegate: ChildViewControllerDelegate?
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var liveTvView: UIView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var avatarImage: UIImageView!
    @IBOutlet weak var notificationBtn: UIButton!
    
    @IBOutlet weak var liveTVActivityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var adView: UIView!
    
    var vm = ThemeTwoVM()
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: K.NotificationCenterReloads.reloadTheme), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: K.NotificationCenterReloads.themeTwoPush), object: nil)
        NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
//        vm.avPlayer.removeObserver(self, forKeyPath: "timeControlStatus")
//        vm.playerItem.removeObserver(self, forKeyPath: "status")
        
        if let playerItem = vm.playerItem{
            playerItem.removeObserver(self, forKeyPath: "status")
        }
        if let avPlayer = vm.avPlayer {
            avPlayer.removeObserver(self, forKeyPath: "timeControlStatus")
            avPlayer.pause()
        }
        
        NotificationCenter.default.removeObserver(self, name: AVAudioSession.routeChangeNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
        
        if MyListDataTemp.shareInstance.favListingData?.showData == nil {
            MyListDataTemp.shareInstance.favListingData = FavouriteListingDM.ResultData(totalRecords: nil, showData: FavouriteListingDM.ResultData.ShowData(hindi: [],english: []),videoData: [],gameData: [],singKaraokeData: [],audioData: [])
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.navigationBar.barStyle = .black
        setNeedsStatusBarAppearanceUpdate()
        
        K.GVar.topView = .theme2
        if let player = vm.avPlayer{
            player.play()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        vm.setData()
        if vm.playerLayer != nil{
            vm.playerLayer.frame = liveTvView.bounds
        }
    }
    
    @IBAction func sideBarBtnTapped(_ sender: UIButton) {
        self.sideMenuController?.revealMenu()
    }
    
    @IBAction func notificationBtnTapped(_ sender: UIButton) {
//        CommonNwCall.shareInstance.getUserNotification(vc: self) { isDone in
//            if isDone{
//                let sb = UIStoryboard(name: K.StoryBoard.theme, bundle: nil)
//                let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Home.userNotificationVC) as! UserNotificationVC
//                self.navigationController?.pushViewController(vcPush, animated: true)
//            }
//        }
        let sb = UIStoryboard(name: K.StoryBoard.theme, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Home.userNotificationVC) as! UserNotificationVC
        self.navigationController?.pushViewController(vcPush, animated: true)
    }
    
    @IBAction func playTrailer(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        let item = JwPlayerItemCreate(url: APIEndPoints.StaticURLs.masilaUrl, poster: nil, titles: "Masila")
        JWPlayerManager.shared.presentPlayer(from: self, playerItems: [item], contentType: .trailer, videoIDs: [0])
    }
    
    // MARK: - Handler for AvPlayer

    func startMonitoringNetwork() {
        if vm.isNetworkMonitored{return}
        vm.isNetworkMonitored = true
        vm.monitor.pathUpdateHandler = { [weak self] path in
            guard let self else{return}
            if path.status == .satisfied {
                // when internet is back we have to setup player again
                vm.monitor.cancel()
                DispatchQueue.main.async {
                    self.vm.avPlayer = nil
                    self.vm.setupAvPlayer()
                }
                print("network connection is back")
            } else {
                print("No connection.")
                
            }
            print("Is on WiFi: \(path.usesInterfaceType(.wifi))")
            print("Is on Cellular: \(path.usesInterfaceType(.cellular))")
        }
        
        vm.monitor.start(queue: vm.queue)
        vm.isNetworkMonitored = true
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        //this will oberver if player loads the url or fails
        if keyPath == "status" {
            if vm.playerItem.status == .readyToPlay {
                print("Theme 2 Player is ready to play")
                vm.avPlayer.play()
            } else if vm.playerItem.status == .failed {
                print("Theme 2 Player failed to load")
                if vm.reachability?.isReachable == true{
                    vm.setupAvPlayer()
                }
            }
        }
        
        //this will give status of buffering, play pause.
        if keyPath == "timeControlStatus" {
            if let player = object as? AVPlayer {
                switch player.timeControlStatus {
                case .waitingToPlayAtSpecifiedRate:
                    print("Theme 2 Player Buffering...")
                    vm.startStopActivity(isStart: true)
                    switch vm.reachability?.isReachable{
                    case true:
                        break
                    case false:
                        /*
                         Start monitoring when the player buffers and there is not internet connection
                         */
                        print("Monitoring Started")
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){ [weak self] in
                            guard let self else{return}
                            self.startMonitoringNetwork()
                        }
                    default:
                        break
                    }
                case .playing:
                    print("Theme 2 Player Playing")
                    vm.startStopActivity(isStart: false)
                case .paused:
                    print("Theme 2 Player Paused")
                    
                    // check if app is in background return it
                    if UIApplication.shared.applicationState == .background {return}
                    if let rootViewController = UIApplication.shared.mainKeyWindow?.rootViewController {
                        if let topVC = topVC(in: rootViewController) {
                            if topVC is HomeVC{
                                vm.avPlayer.play()
                            } else {
                                print("The top view controller is not HomeVC")
                            }
                        } else {
                            print("No top view controller found")
                        }
                    }
                    
                @unknown default:
                    print("Theme 2 Player Unknown status")
                }
            }
        }
    }
    
}

// MARK: - CollectionView DataSource Delegate

extension ThemeTwoVC : CollectionViewSRC{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        vm.cellData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.Theme.homeExploreCell, for: indexPath) as! HomeExploreCell
        cell.setData(data : vm.cellData[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.row{
        case 0:
            PersistentStorage.shared.addRadioCount()
            vm.checkType(action: .radio)
        case 1:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .liveTV)
        case 2:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .webseries)
        case 3:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .games)
        case 4:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .audioBooks)
        case 5:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .karaoke)
        case 6:
            PersistentStorage.shared.addOthersCount()
            vm.checkType(action: .shop)
        default:
            break
        }
    }
}

// MARK: - Collection Flow Layout

extension ThemeTwoVC : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemsPerRow: CGFloat = 3
        let paddingSpace = 5 * (itemsPerRow + 1)
        let availableWidth = collectionView.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow
        return CGSize(width: widthPerItem, height: widthPerItem + (widthPerItem / 6))
    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
//    }
}


// MARK: - Google Ad Banner Delegate

extension ThemeTwoVC : GADBannerViewDelegate{
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("bannerViewDidReceiveAd")
        adView.isHidden = false
        bannerView.backgroundColor = #colorLiteral(red: 0.01960784314, green: 0, blue: 0.2196078431, alpha: 1)
        bannerView.alpha = 0
        UIView.animate(withDuration: 0.3, animations: {
            bannerView.alpha = 1
        })
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        self.adView.isHidden = true
        print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
        print("bannerViewDidRecordImpression")
    }
    
    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillPresentScreen")
    }
    
    func bannerViewDidRecordClick(_ bannerView: GADBannerView) {
        print("bannerViewDidRecordClick")
    }
    
    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillDIsmissScreen")
    }
    
    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewDidDismissScreen")
    }
}
