//
//  GamesListVM.swift
//  WOKA
//
//  Created by MacBook Pro on 04/07/24.
//

import UIKit
import Alamofire

class GamesListVM{
    
    weak var vc : GamesListVC!
    var gameData = [GamesListDM.GameDatum]()
    var indexToLoad = 0
    var pageNo = 0
    var maxHeaderHeight = 0.0

    
    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 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()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
//                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let dataCount = data.data?.totalRecords, let data = data.data?.gameData else{return}
                    self.gameData.append(contentsOf: data)
                    self.vc.gamesListingTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height + 100
                    self.vc.gamesListingTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.gamesListingTableView.contentSize.height
                    
                    /*
                     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.forPage == AdsEnum.games.rawValue}).first, let bannerImage = gamesAd.bannerImage, let buttonImage = gamesAd.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()
                        }
                    }

                    
                    self.stopShimmer()
                    
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
                    
                    if self.gameData.count == dataCount{
                        self.vc.loadMoreBtn.isHidden = true
                    }else{
                        self.vc.loadMoreBtn.isHidden = false
                    }
                    
//                    if self.gameData.count.isMultiple(of: 5) && !self.stopFetch{
//                        // if not multiple of 10, means more data can be there, show more btn
//                        self.vc.loadMoreBtn.isHidden = false
//                    }else{
//                        self.stopFetch = true
//                        self.vc.loadMoreBtn.isHidden = true
//                    }
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                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) { [unowned self] isDone in
                    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) { [unowned self] isDone in
                    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) { [unowned self] isDone in
                    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){ [unowned self] isDone in
                    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
                        }
                    }
                }
            }
        }
    }

}
