//
//  WebSeriesVM.swift
//  WOKA
//
//  Created by MacBook Pro on 18/06/24.
//

import Foundation
import Alamofire
import GoogleMobileAds

class WebSeriesVM{
    
    weak var vc : WebSeriesVC!
    var continueWatchingData = [ContinueWatchingDM.ResultData]()
    var categoryListingData = [CategoryListingDM.ResultData]()
    
    var showData = [WebSeriesShowListDM.ShowDatum]()
    
    let dropDownModule = DropDown()
    var dataSource = [String]()
//    var tempCount = 2
    
    //Static url for masila
////    var masilaUrl = "https://content.jwplatform.com/videos/Iygt11AD-Ysj2G4DQ.mp4"
//    var masilaUrl = "https://cdn.jwplayer.com/manifests/Iygt11AD.m3u8"
    var pageNo = 0
    var stopFetch = false
    
    var maxHeaderHeight = 0.0
    
    var headerBannerView = GADBannerView()
    var masilaBannerView = GADBannerView()
    
    func initView(){
        
//        let heightMultiplier: CGFloat = 0.257511
//        let heightMultiplier: CGFloat = 0.29

        // Get the current screen height
//        let currentScreenHeight = UIScreen.main.bounds.height

        // Calculate the new view height based on the multiplier
//        maxHeaderHeight = currentScreenHeight * heightMultiplier
        
        //Set Header height
        maxHeaderHeight = UIScreen.main.bounds.width * 0.55
        vc.headerHeight.constant = maxHeaderHeight
        
        setupCell()

        startShimmer()
        vc.scrollView.indicatorStyle = .white // or .white

        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.title = "WEB SERIES".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))
        
        getCategoryListing()
        
        // for the first load always send hindi as it is default category
        self.getShowListing(categoryID: 18)
        
        vc.languageStack.addTapGesture { [weak self] in
            guard let self else {return}
            dropDownModule.show()
            self.vc.expandBtn.setImage(UIImage(named: "SupportUpArrow"), for: .normal)
        }
        
        checkAds()
        
        /*
         MAke logic for ads
         */
//        if let adsData = AuthFunc.shareInstance.adsData{
//            // check if ads data contains ad for webseries
//            if let webSeriesAd = adsData.result?.filter({$0.forPage == AdsEnum.web_series.rawValue}).first{
//                vc.headerViewImage.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)
//                    }
//                }
//            }
//        }
    }
    
    func checkAds(){
        
        /*
         This is test ad.
         */
        
        /*
         MAke logic for ads
         */
        if let adsData = AuthFunc.shareInstance.adsData, let webSeriesAd = adsData.result?.filter({$0.forPage == AdsEnum.web_series.rawValue}).first{
            // check if ads data contains ad for webseries
            if let bannerImage = webSeriesAd.bannerImage, let buttonImage = webSeriesAd.buttonImage{
                vc.headerViewImage.imageURL(bannerImage, color: .white)
                vc.headerBtn.setTitle("", for: .normal)
                vc.headerViewLabel.text = ""
                vc.headerViewLabelHeight.constant = 10
                vc.headerBtn.backgroundColor = .clear
                vc.headerBtn.sd_setBackgroundImage(with: URL(string:buttonImage), for: .normal)
                
                vc.headerViewImage.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{
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
                guard let self else{return}

                AdReusable.sharedInstance.setupBannerAd(bannerView: self.headerBannerView, in: vc.headerView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self.vc)
                AdReusable.sharedInstance.setupBannerAd(bannerView: self.masilaBannerView, in: vc.masilaTrailerView, adUnitID: K.GoogleAdIDs.themeTwo, viewController: self.vc, height: 8, width: 15)
            })
//            let viewWidth = vc.headerView.frame.inset(by: vc.headerView.safeAreaInsets).width
//
//            // Here the current interface orientation is used. Use
//            // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or
//            // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a
//            // particular orientation,
//            let adaptiveSize = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
//            headerBannerView = GADBannerView(adSize: adaptiveSize)
//            headerBannerView.delegate = self.vc
//            headerBannerView.center = vc.headerView.center
//            
//            headerBannerView.frame = CGRect(x: 0, y: 0, width: vc.headerView.frame.width, height: vc.headerView.frame.height)
//            vc.headerView.addSubview(headerBannerView)
//            headerBannerView.adUnitID = "K.GoogleAdIDs.themeTwo"
//            headerBannerView.rootViewController = self.vc
//            headerBannerView.load(GADRequest())
//            headerBannerView.layoutIfNeeded()
//
//            var bannerView2 = GADBannerView()
//
//            let viewWidth2 = vc.masilaTrailerView.frame.inset(by: vc.masilaTrailerView.safeAreaInsets).width
//
//            // Here the current interface orientation is used. Use
//            // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or
//            // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a
//            // particular orientation,
//            let adaptiveSize2 = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth2)
//            bannerView2 = GADBannerView(adSize: adaptiveSize2)
//            
//            bannerView2.center = vc.masilaTrailerView.center
//            
//            bannerView2.frame = CGRect(x: 0, y: 0, width: vc.masilaTrailerView.frame.width, height: vc.masilaTrailerView.frame.height)
//            vc.masilaTrailerView.addSubview(bannerView2)
//            bannerView2.adUnitID = K.GoogleAdIDs.themeTwo
//            bannerView2.rootViewController = self.vc
//            bannerView2.load(GADRequest())
//            bannerView2.layoutIfNeeded()
        }
    }
    
    func startShimmer(){
        vc.headerView.startShimmer()
        vc.masilaTrailerView.startShimmer()
        vc.videoLanguageView.startShimmer()
    }
    
    func stopShimmer(){
        self.vc.headerView.stopShimmer()
        self.vc.masilaTrailerView.stopShimmer()
        self.vc.videoLanguageView.stopShimmer()
    }
    
    func setupCell(){
        vc.continueWatchingCV.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesCell)
        vc.continueWatchingCV.delegate = vc.self
        vc.continueWatchingCV.dataSource = vc.self
        
        vc.showListingTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesShowListingCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesShowListingCell)
        vc.showListingTableView.delegate = vc.self
        vc.showListingTableView.dataSource = vc.self
    }
    
    func updateTableHeight(){
        self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height + 100
        self.vc.showListingTableView.layoutIfNeeded()
        self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height
    }
    
    // MARK: - DropDown

    func initDropDown(){
        dropDownModule.anchorView = vc.languageStack
        dropDownModule.dataSource = dataSource
        dropDownModule.cornerRadius = 10
        dropDownModule.bottomOffset = CGPoint(x: 0, y:(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.topOffset = CGPoint(x: 0, y:-(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.direction = .bottom
        dropDownModule.textFont = FontCustom.shareInstance.customFont(fontName: .Exo2_Bold, size: 14)
        dropDownModule.shadowColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.backgroundColor = .white
        dropDownModule.shadowOffset = CGSize(width: 0, height: 1)
        dropDownModule.separatorColor = UIColor.lightGray
        dropDownModule.width = vc.languageStack.frame.width
        dropDownModule.selectionBackgroundColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.selectedTextColor = .white
        dropDownModule.selectRow(at: 0)
        
        // handle if user clicks outside
        dropDownModule.cancelAction = { [weak self] in
            guard let self else{return}
            PersistentStorage.shared.addOthersCount()
            vc.expandBtn.setImage(UIImage(named: "SupportBottomArrow"), for: .normal)
        }
        
        dropDownModule.selectionAction = { [weak self] (index: Int, item: String) in
            PersistentStorage.shared.addOthersCount()
            guard let self else{return}
            vc.languageLabel.text = item
            vc.expandBtn.setImage(UIImage(named: "SupportBottomArrow"), for: .normal)
            
            //if the language is changed call the showlisting api
            if let id = categoryListingData[index].id {
                pageNo = 0
                getShowListing(categoryID: id,languageChange: true)
            }
            
        }
    }
    // MARK: - Api Calls

    func getContinueWatching(){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["post_type" : 3] // 3- webseries
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.continue_watching, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<ContinueWatchingDM>, 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: 2)
            }
        }
    }
    
    func getShowListing(categoryID : Int, isBtnClick : Bool = false, languageChange : Bool = false){
//        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["category_id" : categoryID,
                                   "api_version" : "v2",
                                   "start" : pageNo,
                                   "limit": 6] // from category listing api , default will be 1
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.watch_show_listing, method: .post,parameters: params,headers: headers, queue: QueueHelper.utilityGroup) { [weak self](result : Result<BaseResponseModel<WebSeriesShowListDM>, 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)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let dataCount = data.data?.totalRecords , let data = data.data?.showData else{return}
                    if languageChange{
                        self.showData.removeAll()
                        self.showData.append(contentsOf: data)
                    }else{
                        self.showData.append(contentsOf: data)
                    }
                    
                    self.stopShimmer()
                    self.vc.scrollView.isScrollEnabled = true
                    self.vc.showListingTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height + 100
                    self.vc.showListingTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height
                    
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
                    
                    if self.showData.count == dataCount{
                        self.vc.loadMoreBtn.isHidden = true
                    }else{
                        self.vc.loadMoreBtn.isHidden = false
                    }
                    
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                vc.toast(msg: error.localizedDescription , time: K.ConstantString.errorTime)
            }
        }
    }
    
    func getCategoryListing(){
//        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["module_id" : 7] // 7 - webseries
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.category_listing, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<CategoryListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    self.stopShimmer()
                    vc.noDataView.isHidden = false
                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    self.categoryListingData = data
                    dataSource = categoryListingData.map({$0.categoryName ?? "Unknown"})
                    getContinueWatching()
                    initDropDown()
                default:
                    self.stopShimmer()
                    vc.noDataView.isHidden = false
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                self.stopShimmer()
                Utilities.dismissProgressHUD()
                vc.noDataView.isHidden = false
                vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }

}
