//
//  AudioBookHomeVM.swift
//  WOKA
//
//  Created by MacBook Pro on 02/07/24.
//

import Foundation
import Alamofire

class AudioBookHomeVM{
    
    weak var vc : AudioBookHomeVC!
    var continueWatchingData = [ListenAudioListingDM.AudioDatum]()
    var audioListData = [ListenAudioListingDM.AudioDatum]()
    
    var headerData : ListenAudioListingDM.AudioDatum?

//    var indexToLoad = 0
    var pageNo = 0
    var maxHeaderHeight = 0.0

    func initView(){
        vc.scrollView.indicatorStyle = .white // or .white
        startShimmer()
        setupCell()
        getShowListing()
        
        //Set banner height
        maxHeaderHeight = UIScreen.main.bounds.width * 0.55
        vc.headerHeight.constant = maxHeaderHeight
    }
    
    func startShimmer(){
        vc.headerView.startShimmer()
        vc.listenView.startShimmer()
    }
    
    func updateTableHeight(){
        self.vc.tableHeight.constant = self.vc.audioListingTableView.contentSize.height + 100
        self.vc.audioListingTableView.layoutIfNeeded()
        self.vc.tableHeight.constant = self.vc.audioListingTableView.contentSize.height
    }
    
    func setHeaderData(){
//        if indexToLoad > continueWatchingData.count {
//            return
//        }
        guard let headerData else{return}
        
        if let url = headerData.thumbnailPath{
            self.vc.headerImage.imageURL(url, color: .white)
        }
        
        if AuthFunc.shareInstance.getDefaultLanguage() == .english{
            let englishData = headerData.contentMoreDetails?.filter({$0.languageMasterID == 1}).first
            vc.headerTitleLabel.text = englishData?.title
        }else{
            let hindiData = headerData.contentMoreDetails?.filter({$0.languageMasterID == 2}).first
            vc.headerTitleLabel.text = hindiData?.title
        }
    }
    
    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.audioListingTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesShowListingCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesShowListingCell)
        vc.audioListingTableView.delegate = vc.self
        vc.audioListingTableView.dataSource = vc.self
    }
    
    // MARK: - Api Calls
    
    func getContinueWatching(){
        //        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["post_type" : 7] // 7 - audio
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.continue_watching, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<ContinueAudioListDM>, 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(isBtnClick : Bool = false){
        //        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["api_version" : "v2",
                                   "start" : pageNo,
                                   "limit": 6]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.AudioBooks.listen_audio_listing, method: .post, parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<ListenAudioListingDM>, 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()
                    getContinueWatching()
                    guard let dataCount = data.data?.totalRecords ,let data = data.data?.audioData else{return}
                    self.audioListData.append(contentsOf: data)
                    self.vc.audioListingTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.audioListingTableView.contentSize.height + 100
                    self.vc.audioListingTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.audioListingTableView.contentSize.height
                    /*
                     MAke logic for ads
                     */
                    if let adsData = AuthFunc.shareInstance.adsData{
                        // check if ads data contains ad for webseries
                        if let audioBooksAd = adsData.result?.filter({$0.forPage == AdsEnum.audioBooks.rawValue}).first, let bannerImage = audioBooksAd.bannerImage, let buttonImage = audioBooksAd.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{
                                self.headerData = self.audioListData.first
                                self.setHeaderData()
                            }
                        }
                    }else{
                        if !isBtnClick{
                            self.headerData = self.audioListData.first
                            self.setHeaderData()
                        }
                    }
                    
                    self.stopShimmer()
                    
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
                    
                    if self.audioListData.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)
                self.stopShimmer()
                self.vc.noDataView.isHidden = false
            }
        }
    }
    
    func stopShimmer(){
        self.vc.headerView.stopShimmer()
        vc.listenView.stopShimmer()
        //        self.vc.masilaTrailerView.stopShimmer()
        //        self.vc.videoLanguageView.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 {
                // if is fav then remove it
                LikeFavCommonFunc.shareInstance.removeFavourite(postID: postID, postType: postType, categoryID: 0, vc: self.vc) { [unowned self] isDone in
                    if isDone{
                        if let showListIndex = audioListData.firstIndex(where: { $0.id == postID }){
                            audioListData[showListIndex].markAsFavourite = false
                            vc.audioListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                            
                            K.GVar.reloadMyListAudioBooks = true
//                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                if let indexRemove = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == postID}){
//                                    MyListDataTemp.shareInstance.favListingData?.audioData?.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.reloadMyListAudioBooks = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                if let indexRemove = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == postID}){
//                                    MyListDataTemp.shareInstance.favListingData?.audioData?.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 = audioListData.firstIndex(where: { $0.id == postID }){
                            audioListData[showListIndex].markAsFavourite = true
                            vc.audioListingTableView.reloadRows(at: [IndexPath(row: showListIndex, section: 0)],with: .none)
                            K.GVar.reloadMyListAudioBooks = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                let audioData = audioListData[showListIndex]
//                                MyListDataTemp.shareInstance.favListingData?.audioData?.append(audioData)
//                                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.reloadMyListAudioBooks = true
                            // MyList Update
//                            if MyListDataTemp.shareInstance.isDatafetched{
//                                if MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == postID}) == nil{
//                                    let audioData = continueWatchingData[continueWatchingIndex]
//                                    MyListDataTemp.shareInstance.favListingData?.audioData?.append(audioData)
//                                    K.GVar.myListSoftReload = true
//                                }
//                            }
                        }
                        
                    }
                }
            }
            return
        case .liked:
            guard let isLiked else{return}
            if isLiked{
                // Unlike
                LikeFavCommonFunc.shareInstance.unlikePost(postID: postID, postType: postType, vc: self.vc) { [unowned self] isDone in
                    if isDone{
                        if let showListIndex = audioListData.firstIndex(where: { $0.id == postID }){
                            audioListData[showListIndex].isLiked = false
                            audioListData[showListIndex].likesCount! -= 1
                            vc.audioListingTableView.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 continue watching
                         */
                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == postID}){
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! -= 1
                            
                            K.GVar.myListSoftReload = true
                        }
                    }
                }
            }else{
                //Like
                LikeFavCommonFunc.shareInstance.likePost(postID: postID, postType: postType, vc: self.vc){ [unowned self] isDone in
                    if isDone{
                        if let showListIndex = audioListData.firstIndex(where: { $0.id == postID }){
                            audioListData[showListIndex].isLiked = true
                            audioListData[showListIndex].likesCount! += 1
                            vc.audioListingTableView.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 continue watching
                         */
                        if let index = MyListDataTemp.shareInstance.favListingData?.audioData?.firstIndex(where: {$0.id == postID}){
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.audioData?[index].likesCount! += 1
                            
                            K.GVar.myListSoftReload = true
                        }
                    }
                }
            }
        }
    }
}
