Files
Woka_Native_iOS/WOKA/Games/ViewModel/GamesListVM.swift
2024-10-19 11:29:23 +05:30

303 lines
14 KiB
Swift

//
// GamesListVM.swift
// WOKA
//
// Created by MacBook Pro on 04/07/24.
//
import UIKit
import Alamofire
import GoogleMobileAds
class GamesListVM{
weak var vc : GamesListVC!
var gameData = [GamesListDM.GameDatum]()
var indexToLoad = 0
var maxHeaderHeight = 0.0
// PAgination variables
var pageNo = 0
var isGameDataLoading = false
var totalDataCount = 0 // this will hold the total count from api
var headerBannerView = GADBannerView()
var headerBannerBottomView = GADBannerView()
let feedbackGenerator = UIImpactFeedbackGenerator(style: .rigid)
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)
self.vc.view.applyGradient(colors: [color1,color2], startPoint: .Point.left.point , endPoint: .Point.right.point)
startShimmer()
getGamesListing()
//Set banner height
maxHeaderHeight = UIScreen.main.bounds.width * 0.55
vc.headerHeight.constant = maxHeaderHeight
}
func checkAds(){
/*
This is test ad.
*/
/*
MAke logic for ads
*/
if let adsData = AuthFunc.shareInstance.adsData, let gamesAd = adsData.result?.filter({$0.slug == AdsEnum.games.rawValue}).first{
// check if ads data contains ad for webseries
if let bannerImage = gamesAd.advertisement?.bannerImage, let buttonImage = gamesAd.advertisement?.buttonImage{
vc.headerImage.imageURL(bannerImage, color: .white)
vc.headerBtn.setTitle("", for: .normal)
vc.headerTitleLabel.text = ""
vc.headerTitleHeight.constant = 10
vc.headerBtn.backgroundColor = .clear
vc.headerBtn.sd_setBackgroundImage(with: URL(string:buttonImage), for: .normal)
vc.headerImage.addTapGesture {
if let adID = gamesAd.id{
PersistentStorage.shared.addAdsCount(adID: adID ,clicks: 1)
}
if let adLink = gamesAd.advertisement?.adLink ,let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
}else if gamesAd.googleAd != nil{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: { [weak self] in
guard let self else{return}
AdReusable.sharedInstance.setupBannerAd(bannerView: headerBannerView, in:vc.headerView, adUnitID: K.GoogleAdIDs.games1, viewController: self.vc)
AdReusable.sharedInstance.setupBannerAd(bannerView: headerBannerBottomView, in: vc.gamesLoadingView, adUnitID: K.GoogleAdIDs.games2, viewController: self.vc, height: 8, width: 15)
})
}else{
setHeaderData()
}
}else{
setHeaderData()
}
}
func setupCell(){
vc.gamesListingTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesShowListingCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesShowListingCell)
vc.gamesListingTableView.delegate = vc.self
vc.gamesListingTableView.dataSource = vc.self
}
func startShimmer(){
vc.headerView.startShimmer()
vc.gamesLoadingView.startShimmer()
}
func stopShimmer(){
vc.headerView.stopShimmer()
vc.gamesLoadingView.stopShimmer()
}
func setHeaderData(){
let data = gameData[indexToLoad]
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 updateTableHeight(){
self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height + 100
self.vc.gamesListingTableView.layoutIfNeeded()
self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height
}
// MARK: - Get Games Data
func getGamesListing(isBtnClick : Bool = false){
let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
let params : Parameters = ["api_version" : "v2",
"start" : pageNo,
"limit": 5]
NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Games.game_listing, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<GamesListDM>, NetworkManager.APIError>) in
switch result{
case .success(let data):
guard let self else{
Utilities.dismissProgressHUD()
self?.isGameDataLoading = false
return
}
switch data.success{
case 0:
/*
Error
*/
Utilities.dismissProgressHUD()
self.isGameDataLoading = false
self.vc.loadMoreActivityIndicator.stopAnimating()
self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
// vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
case 1:
Utilities.dismissProgressHUD()
self.isGameDataLoading = false
self.pageNo += 1
guard let dataCount = data.data?.totalRecords, let data = data.data?.gameData else{return}
//update the total data count
self.totalDataCount = dataCount
self.gameData.append(contentsOf: data)
//Reload games tableview and increase height inside the scrollview
self.vc.gamesListingTableView.reloadData()
if !isBtnClick{
HapticFeedbackGenerator.shared.rigidImpact()
self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height + 100
}
self.vc.gamesListingTableView.layoutIfNeeded()
self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height
self.stopShimmer()
self.vc.loadMoreActivityIndicator.stopAnimating()
self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
checkAds()
/*
MAke logic for ads
// */
// if let adsData = AuthFunc.shareInstance.adsData{
// // check if ads data contains ad for webseries
// if let gamesAd = adsData.result?.filter({$0.slug == AdsEnum.games.rawValue}).first, let bannerImage = gamesAd.advertisement?.bannerImage, let buttonImage = gamesAd.advertisement?.buttonImage{
// vc.headerImage.imageURL(bannerImage, color: .white)
// vc.headerBtn.setTitle("", for: .normal)
// vc.headerTitleLabel.text = ""
// vc.headerTitleHeight.constant = 10
// vc.headerBtn.backgroundColor = .clear
// vc.headerBtn.sd_setBackgroundImage(with: URL(string:buttonImage), for: .normal)
// }else{
// if !isBtnClick{
// setHeaderData()
// }
// }
// }else{
// if !isBtnClick{
// setHeaderData()
// }
// }
default:
self.isGameDataLoading = false
}
case .failure(let error):
guard let self else{
Utilities.dismissProgressHUD()
self?.isGameDataLoading = false
return
}
Utilities.dismissProgressHUD()
self.isGameDataLoading = false
self.stopShimmer()
self.vc.noDataView.isHidden = false
vc.toast(msg: error.localizedDescription, time: K.ConstantString.errorTime)
}
}
}
// MARK: - Update Fav Likes
func updateFavLikes(type : FavCellCLick, index : Int){
let data = gameData[index]
if let postID = data.id{
PersistentStorage.shared.addGamesCount(postID: postID)
}
switch type {
case .favourite:
guard let isFav = data.markAsFavourite ,let postID = data.id,let postType = data.contentMoreDetails?.first?.postType else{return}
if isFav == true {
LikeFavCommonFunc.shareInstance.removeFavourite(postID: postID, postType: postType, categoryID: 0, vc: self.vc) { [weak self] isDone in
guard let self else{return}
if isDone{
gameData[index].markAsFavourite = false
vc.gamesListingTableView.reloadRows(at: [IndexPath(row: index, section: 0)],with: .none)
K.GVar.reloadGames = true
// MyList Update
// if MyListDataTemp.shareInstance.isDatafetched{
// if let indexRemove = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == postID}){
// MyListDataTemp.shareInstance.favListingData?.gameData?.remove(at: indexRemove)
// K.GVar.myListSoftReload = true
// }
// }
}
}
}else{
LikeFavCommonFunc.shareInstance.addFavourite(postID: postID, postType: postType, categoryID: 0, vc: self.vc) { [weak self] isDone in
guard let self else{return}
if isDone{
gameData[index].markAsFavourite = true
vc.gamesListingTableView.reloadRows(at: [IndexPath(row: index, section: 0)],with: .none)
K.GVar.reloadGames = true
// MyList Update
// if MyListDataTemp.shareInstance.isDatafetched{
// let gameData = gameData[index]
// MyListDataTemp.shareInstance.favListingData?.gameData?.append(gameData)
// K.GVar.myListSoftReload = true
// }
}
}
}
return
case .liked:
guard let isLiked = data.isLiked ,let postID = data.id,let postType = data.contentMoreDetails?.first?.postType else{return}
if isLiked{
LikeFavCommonFunc.shareInstance.unlikePost(postID: postID, postType: postType, vc: self.vc) { [weak self] isDone in
guard let self else{return}
if isDone{
gameData[index].isLiked = false
gameData[index].likesCount! -= 1
vc.gamesListingTableView.reloadRows(at: [IndexPath(row: index, section: 0)],with: .none)
/*
Check if the data is in continue watching
*/
if let index = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == postID}){
MyListDataTemp.shareInstance.favListingData?.gameData?[index].isLiked = false
MyListDataTemp.shareInstance.favListingData?.gameData?[index].likesCount! -= 1
K.GVar.myListSoftReload = true
}
}
}
}else{
LikeFavCommonFunc.shareInstance.likePost(postID: postID, postType: postType, vc: self.vc){ [weak self] isDone in
guard let self else{return}
if isDone{
gameData[index].isLiked = true
gameData[index].likesCount! += 1
vc.gamesListingTableView.reloadRows(at: [IndexPath(row: index, section: 0)],with: .none)
/*
Check if the data is in continue watching
*/
if let index = MyListDataTemp.shareInstance.favListingData?.gameData?.firstIndex(where: {$0.id == postID}){
MyListDataTemp.shareInstance.favListingData?.gameData?[index].isLiked = true
MyListDataTemp.shareInstance.favListingData?.gameData?[index].likesCount! += 1
K.GVar.myListSoftReload = true
}
}
}
}
}
}
}