//
//  KaraokeListingVM.swift
//  WOKA
//
//  Created by Bilal on 05/07/2024.
//

import UIKit
import Alamofire
import GoogleMobileAds

class KaraokeListingVM{
    
    weak var vc : KaraokeListingVC!
    var karaokeListData = [KaraokeListingDM.KaraokeDatum]()
    var continueWatchingData = [KaraokeListingDM.KaraokeDatum]()
    
    var headerData : KaraokeListingDM.KaraokeDatum?
    
    var pageNo = 0
    var maxHeaderHeight = 0.0
    
    var headerBannerView = GADBannerView()
    var headerBannerBottomView = GADBannerView()
    
    func initView(){
        setupCell()
        vc.scrollView.indicatorStyle = .white // or .white
        let color1 = #colorLiteral(red: 0.8, green: 0.6078431373, blue: 0.1098039216, alpha: 1)
        let color2 = #colorLiteral(red: 0.8, green: 0.2901960784, blue: 0.1098039216, alpha: 1)
        vc.title = "KARAOKE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        startShimmer()
        
        getKaraokeListing()
        
        //Set banner height
        maxHeaderHeight = UIScreen.main.bounds.width * 0.55
        vc.headerHeight.constant = maxHeaderHeight
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
            guard let self else{return}
            checkAds()
        })
    }
    
    func setupCell(){
        vc.continueWatchingCV.register(UINib(nibName: K.CellIdentifier.AudioBooks.continueAudioCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.AudioBooks.continueAudioCell)
        vc.continueWatchingCV.delegate = vc.self
        vc.continueWatchingCV.dataSource = vc.self
        
        vc.karaokeListingTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesShowListingCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesShowListingCell)
        vc.karaokeListingTableView.delegate = vc.self
        vc.karaokeListingTableView.dataSource = vc.self
    }
    
    func updateTableHeight(){
        self.vc.tableHeight.constant = self.vc.karaokeListingTableView.contentSize.height + 100
        self.vc.karaokeListingTableView.layoutIfNeeded()
        self.vc.tableHeight.constant = self.vc.karaokeListingTableView.contentSize.height
    }
    
    func setHeaderData(){
        guard let data = self.headerData else{return}
        
        if let url = data.thumbnailPath{
            self.vc.headerImage.imageURL(url, color: .white)
        }
        
        if AuthFunc.shareInstance.getDefaultLanguage() == .english{
            let englishData = data.contentMoreDetails?.filter({$0.languageMasterID == 1}).first
            vc.headerTitleLabel.text = englishData?.title
        }else{
            let hindiData = data.contentMoreDetails?.filter({$0.languageMasterID == 2}).first
            vc.headerTitleLabel.text = hindiData?.title
        }
    }
    
    func checkAds(){
        
        /*
         This is test ad.
         */
        
        /*
         MAke logic for ads
         */
        if let adsData = AuthFunc.shareInstance.adsData, let webSeriesAd = adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first{
            // check if ads data contains ad for webseries
            if let bannerImage = webSeriesAd.bannerImage, let buttonImage = webSeriesAd.buttonImage{
                vc.headerImage.imageURL(bannerImage, color: .white)
                vc.headerBtn.setTitle("", for: .normal)
                vc.headerTitleLabel.text = ""
                vc.headerViewLabelHeight.constant = 10
                vc.headerBtn.backgroundColor = .clear
                vc.headerBtn.sd_setBackgroundImage(with: URL(string:buttonImage), for: .normal)
                
                vc.headerImage.addTapGesture {
                    if let adID = webSeriesAd.id{
                        PersistentStorage.shared.addAdsCount(adID: adID ,clicks: 1)
                    }
                    if let adLink = webSeriesAd.adLink ,let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url)
                    }
                }
            }
        }else{
            AdReusable.sharedInstance.setupBannerAd(bannerView: self.headerBannerView, in: vc.headerView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self.vc)
            AdReusable.sharedInstance.setupBannerAd(bannerView: self.headerBannerBottomView, in: vc.selectedShowView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self.vc, height: 8, width: 15)
        }
    }
    
    // MARK: - GetKaraoke Listing

    func getContinueWatching(){
        //        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["post_type" : 8] // 8 - Karaoke
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.continue_watching, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<KaraokeContinueWatchingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    //                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                    self.vc.continueWatchingStack.isHidden = true
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    if data.count == 0{
                        self.vc.continueWatchingStack.isHidden = true
                    }else{
                        self.vc.continueWatchingStack.isHidden = false
                    }
                    self.continueWatchingData = data
                    self.vc.continueWatchingCV.reloadData()
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                self.vc.continueWatchingStack.isHidden = true
                vc.toast(msg: error.localizedDescription , time: K.ConstantString.errorTime)
            }
        }
    }
    
    func getKaraokeListing(isBtnClick : Bool = false){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["api_version" : "v2",
                                   "start" : pageNo,
                                   "limit": 6]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Karaoke.sing_karaoke_listing, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<KaraokeListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    self.vc.loadMoreBtn.isHidden = true
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
//                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    getContinueWatching()
                    guard let dataCount = data.data?.totalRecords, let data = data.data?.karaokeData else{return}
                    self.karaokeListData.append(contentsOf: data)
                    self.vc.karaokeListingTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.karaokeListingTableView.contentSize.height + 100
                    self.vc.karaokeListingTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.karaokeListingTableView.contentSize.height + 10
                    
                    /*
                     MAke logic for ads
                     */
//                    if let adsData = AuthFunc.shareInstance.adsData{
//                        // check if ads data contains ad for webseries
//                        if let karaokeAd = adsData.result?.filter({$0.forPage == AdsEnum.karaoke.rawValue}).first, let bannerImage = karaokeAd.bannerImage, let buttonImage = karaokeAd.buttonImage{
//                            vc.headerImage.imageURL(bannerImage, color: .white)
//                            vc.headerBtn.setTitle("", for: .normal)
//                            vc.headerTitleLabel.text = ""
//                            vc.headerViewLabelHeight.constant = 10
//                            vc.headerBtn.backgroundColor = .clear
//                            vc.headerBtn.sd_setBackgroundImage(with: URL(string:buttonImage), for: .normal)
//                        }else{
//                            if !isBtnClick{
//                                self.headerData = self.karaokeListData.first
//                                setHeaderData()
//                            }
//                        }
//                    }else{
//                        if !isBtnClick{
//                            self.headerData = self.karaokeListData.first
//                            setHeaderData()
//                        }
//                    }
                    
                    self.stopShimmer()
                    
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
                    
                    if self.karaokeListData.count == dataCount{
                        self.vc.loadMoreBtn.isHidden = true
                    }else{
                        self.vc.loadMoreBtn.isHidden = false
                    }
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    return
                }
                self.stopShimmer()
                vc.toast(msg: error.localizedDescription , time: 2)
                vc.noDataStack.isHidden = false
            }
        }
    }
    
    func startShimmer(){
        vc.headerView.startShimmer()
        vc.selectedShowView.startShimmer()
    }
    
    func stopShimmer(){
        self.vc.headerView.stopShimmer()
        self.vc.selectedShowView.stopShimmer()
    }
    
    // MARK: - Update Fav Likes
    
    func updateFavLikes(type : FavCellCLick, isFav : Bool? ,isLiked : Bool?, postID : Int , postType : Int){
        switch type {
        case .favourite:
            guard let isFav else{return}
            if isFav == true {
                LikeFavCommonFunc.shareInstance.removeFavourite(postID: postID, postType: postType, categoryID: 0, vc: self.vc) { [unowned self] isDone in
                    if isDone{
                        if let showListIndex = karaokeListData.firstIndex(where: { $0.id == postID }){
                            karaokeListData[showListIndex].markAsFavourite = false
                            vc.karaokeListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                            K.GVar.reloadKaraoke = true
//                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                if let indexRemove = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == postID}){
//                                    MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.remove(at: indexRemove)
//                                    K.GVar.myListSoftReload = true
//                                    
//                                }
//                            }
                        }
                        
                        /*
                         Check if the data is in continue watching
                         */
                        if let continueWatchingIndex = continueWatchingData.firstIndex(where: { $0.id == postID }){
                            continueWatchingData[continueWatchingIndex].markAsFavourite = false
                            vc.continueWatchingCV.reloadItems(at: [IndexPath(row: continueWatchingIndex, section: 0)])
                            K.GVar.reloadKaraoke = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                if let indexRemove = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == postID}){
//                                    MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.remove(at: indexRemove)
//                                    K.GVar.myListSoftReload = true
//                                    
//                                }
//                            }
                        }
                    }
                }
            }else{
                LikeFavCommonFunc.shareInstance.addFavourite(postID: postID, postType: postType, categoryID: 0, vc: self.vc) { [unowned self] isDone in
                    if isDone{
                        if let showListIndex = karaokeListData.firstIndex(where: { $0.id == postID }){
                            karaokeListData[showListIndex].markAsFavourite = true
                            vc.karaokeListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                            K.GVar.reloadKaraoke = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                let karaokeData = karaokeListData[showListIndex]
//                                MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.append(karaokeData)
//                                K.GVar.myListSoftReload = true
//                                
//                            }
                        }
                        
                        /*
                         Check if the data is in continue watching
                         */
                        if let continueWatchingIndex = continueWatchingData.firstIndex(where: { $0.id == postID }){
                            continueWatchingData[continueWatchingIndex].markAsFavourite = true
                            vc.continueWatchingCV.reloadItems(at: [IndexPath(row: continueWatchingIndex, section: 0)])
                            K.GVar.reloadKaraoke = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                // if data is updated for main list this ill not work
//                                if MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == postID}) == nil{
//                                    let audioData = continueWatchingData[continueWatchingIndex]
//                                    MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.append(audioData)
//                                    K.GVar.myListSoftReload = true
//                                    
//                                }
//                            }
                        }
                    }
                }
            }
            return
        case .liked:
            guard let isLiked else{return}
            if isLiked{
                LikeFavCommonFunc.shareInstance.unlikePost(postID: postID, postType: postType, vc: self.vc) { [unowned self] isDone in
                    if isDone{
                        if let showListIndex = karaokeListData.firstIndex(where: { $0.id == postID }){
                            karaokeListData[showListIndex].isLiked = false
                            karaokeListData[showListIndex].likesCount! -= 1
                            vc.karaokeListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                        }
                        
                        /*
                         Check if the data is in continue watching
                         */
                        if let continueWatchingIndex = continueWatchingData.firstIndex(where: { $0.id == postID }){
                            continueWatchingData[continueWatchingIndex].isLiked = false
                            continueWatchingData[continueWatchingIndex].likesCount! -= 1
                            vc.continueWatchingCV.reloadItems(at: [IndexPath(row: continueWatchingIndex, section: 0)])
                        }
                        
                        /*
                         Check if the data is in karaoke
                         */
                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == postID}){
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].likesCount! -= 1
                            
                            K.GVar.myListSoftReload = true
                            
                        }
                    }
                }
            }else{
                LikeFavCommonFunc.shareInstance.likePost(postID: postID, postType: postType, vc: self.vc){ [unowned self] isDone in
                    if isDone{
                        if let showListIndex = karaokeListData.firstIndex(where: { $0.id == postID }){
                            karaokeListData[showListIndex].isLiked = true
                            karaokeListData[showListIndex].likesCount! += 1
                            vc.karaokeListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                        }
                        
                        /*
                         Check if the data is in continue watching
                         */
                        if let continueWatchingIndex = continueWatchingData.firstIndex(where: { $0.id == postID }){
                            continueWatchingData[continueWatchingIndex].isLiked = true
                            continueWatchingData[continueWatchingIndex].likesCount! += 1
                            vc.continueWatchingCV.reloadItems(at: [IndexPath(row: continueWatchingIndex, section: 0)])
                        }
                        
                        /*
                         Check if the data is in karaoke mylist
                         */
                        if let index = MyListDataTemp.shareInstance.favListingData?.singKaraokeData?.firstIndex(where: {$0.id == postID}){
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.singKaraokeData?[index].likesCount! += 1
                            
                            K.GVar.myListSoftReload = true
                            
                        }
                    }
                }
            }
        }
    }
}
