// // 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]() // PAgination variables var pageNo = 0 var isShowDataLoading = false var totalDataCount = 0 // this will hold the total count from api var maxHeaderHeight = 0.0 var headerBannerView = GADBannerView() var masilaBannerView = GADBannerView() let feedbackGenerator = UIImpactFeedbackGenerator(style: .rigid) 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() } func checkAds(){ /* First check if webSeries ad is present via slug, then check for Local Ads, if not then check google ads. */ if let adsData = AuthFunc.shareInstance.adsData, let webSeriesAd = adsData.result?.filter({$0.slug == AdsEnum.web_series.rawValue}).first{ // check if ads data contains LocalAD for webseries if let advertisement = webSeriesAd.advertisement,let bannerImage = advertisement.bannerImage, let buttonImage = advertisement.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.advertisement?.adLink ,let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } }else{ // check google ads if webSeriesAd.googleAd != nil{ 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.webSeries1, viewController: self.vc) AdReusable.sharedInstance.setupBannerAd(bannerView: self.masilaBannerView, in: vc.masilaTrailerView, adUnitID: K.GoogleAdIDs.webSeries2, viewController: self.vc, height: 8, width: 15) }) } } } } 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, 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){ let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()] let params : Parameters = ["category_id" : categoryID, "api_version" : "v2", "start" : pageNo, // if page no is 0 then its the first page, if not the increase it by one "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, NetworkManager.APIError>) in switch result{ case .success(let data): guard let self else{ self?.isShowDataLoading = false Utilities.dismissProgressHUD() return } switch data.success{ case 0: /* Error */ Utilities.dismissProgressHUD() self.isShowDataLoading = false vc.toast(msg: data.message ?? "Unrecognised error" , time: 2) case 1: Utilities.dismissProgressHUD() self.isShowDataLoading = false guard let dataCount = data.data?.totalRecords , let data = data.data?.showData else{return} //update the total data count on success. totalDataCount = dataCount //update the page no on success pageNo += 1 //if user changes language from dropdown if languageChange{ self.showData.removeAll() self.showData.append(contentsOf: data) }else{ self.showData.append(contentsOf: data) } //stop the shimmer, enable the scrollview scroll, increase the table height inside the scrollview. self.stopShimmer() self.vc.scrollView.isScrollEnabled = true self.vc.showListingTableView.reloadData() if !isBtnClick{ feedbackGenerator.impactOccurred() self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height + 100 } self.vc.showListingTableView.layoutIfNeeded() self.vc.tableHeight.constant = self.vc.showListingTableView.contentSize.height //stop activity indicator and hide it when stopped self.vc.loadMoreActivityIndicator.stopAnimating() self.vc.loadMoreActivityIndicator.hidesWhenStopped = true default: break } case .failure(let error): guard let self else{ self?.isShowDataLoading = false Utilities.dismissProgressHUD() return } Utilities.dismissProgressHUD() self.isShowDataLoading = false 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, 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) } } } }