//
//  WebSeriesSeasonVM.swift
//  WOKA
//
//  Created by MacBook Pro on 20/06/24.
//

import Foundation
import Alamofire

class WebSeriesSeasonVM{
    
    weak var vc : WebSeriesSeasonVC!
    
    var categoryID : Int?
    
    var episodeSelectedCateogory : Int?
    
    var seasonListingData = [SeasonListingDM.Result]()
    
    var seasonEpisodeData = [EpisodeListingDM.ResultData]()
    
    var teaserData = [TeaserDM.ResultData]()
    
    var showData : WebSeriesShowListDM.ShowDatum?
    
    var indexSelected : Int?
    var pageNo = 0

    func initView(){
        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)
        self.vc.view.applyGradient(colors: [color1,color2], startPoint: .Point.left.point , endPoint: .Point.right.point)
        
        getSeasonListing()
        setupCell()
        setShowData()
        handleTapGesture()
    }
    
    func handleTapGesture(){
        vc.addView.addTapGesture { [weak self] in
            if AuthFunc.shareInstance.guestUserLoginPopUp() {return}

            guard let self ,let indexSelected, let categoryID, let showData, let showID = showData.id, let isFav = showData.markAsFavourite, let postType = showData.contentMoreDetails?.first?.postType else{return}
            PersistentStorage.shared.addWebSeries(catID: categoryID, postID: showID, postType: .series)

            if isFav {
                //remove
                LikeFavCommonFunc.shareInstance.removeFavourite(postID: showID, postType: postType, categoryID: categoryID, vc: self.vc) { isDone in
                    self.showData?.markAsFavourite = false
                    self.showData?.favouriteCategoryIDS = ValueWrapper.stringValue("")
                    self.setShowData()
                    self.vc.likeFavDelegate?.updateRows(index: indexSelected, type: .favourite, isFav: false, isLike: nil, id: showID)
                    
                    //For updating mylist allview
                    K.GVar.reloadMyListAll = 2
                    K.GVar.reloadMyListAllID = showID
                    
                    if self.categoryID == 18{ // hindi
                        K.GVar.reloadHindiWebseries = true
//                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.hindi?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.showData?.hindi?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
                    }else{ // english
                        K.GVar.reloadEnglishWebseries = true
//                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.english?.firstIndex(where: {$0.id == showID}){
//                            MyListDataTemp.shareInstance.favListingData?.showData?.english?.remove(at: index)
//                            K.GVar.myListSoftReload = true
//                        }
                    }
                }
            }else{
                //add
                LikeFavCommonFunc.shareInstance.addFavourite(postID: showID, postType: postType, categoryID: categoryID, vc: self.vc) { isDone in
                    self.showData?.markAsFavourite = true
                    self.showData?.favouriteCategoryIDS = ValueWrapper.stringValue(categoryID.toString())
                    self.setShowData()
                    self.vc.likeFavDelegate?.updateRows(index: indexSelected, type: .favourite, isFav: true, isLike: nil, id: showID)
                    
                    //For updating mylist allview
                    K.GVar.reloadMyListAll = 1
                    K.GVar.reloadMyListAllID = showID
//                    if self.categoryID == 18{ // hindi
//                        guard let showData = self.showData else{return}
//                        MyListDataTemp.shareInstance.favListingData?.showData?.hindi?.append(FavouriteListingDM.ResultData.ShowDatum(id: showData.id, title: showData.title, description: showData.description, thumbnailPath: showData.thumbnailPath, showType: showData.showType, totalSeasons: showData.totalSeasons, totalEpisodes: showData.totalEpisodes, ageRangeMasterID: showData.ageRangeMasterID, genderMasterID: showData.genderMasterID, categoryMasterID: self.categoryID?.toString(), contentMoreDetails: showData.contentMoreDetails, markAsFavourite: showData.markAsFavourite, isLiked: showData.isLiked, likesCount: showData.likesCount, viewsCount: showData.viewsCount, bookmarkCount: showData.bookmarkCount, bookmarkCategoryIDS: "18"))
//                        K.GVar.myListSoftReload = true
//                    }else{ // english
//                        guard let showData = self.showData else{return}
//                        if MyListDataTemp.shareInstance.favListingData?.showData == nil {
//                            MyListDataTemp.shareInstance.favListingData?.showData = []
//                        }
//                        MyListDataTemp.shareInstance.favListingData?.showData?.append(FavouriteListingDM.ResultData.ShowDatum(id: showData.id, title: showData.title, description: showData.description, thumbnailPath: showData.thumbnailPath, showType: showData.showType, totalSeasons: showData.totalSeasons, totalEpisodes: showData.totalEpisodes, ageRangeMasterID: showData.ageRangeMasterID, genderMasterID: showData.genderMasterID, categoryMasterID: self.categoryID?.toString(), contentMoreDetails: showData.contentMoreDetails, markAsFavourite: showData.markAsFavourite, isLiked: showData.isLiked, likesCount: showData.likesCount, viewsCount: showData.viewsCount, bookmarkCount: showData.bookmarkCount, bookmarkCategoryIDS: "1"))
//                        K.GVar.myListSoftReload = true
//                    }
                }
            }
        }
        
        vc.likeView.addTapGesture { [weak self] in
            if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

            guard let self ,let indexSelected, let showData, let showID = showData.id, let isLiked = showData.isLiked, let postType = showData.contentMoreDetails?.first?.postType else{return}
            PersistentStorage.shared.addWebSeries(catID: self.categoryID ?? 0, postID: showID, postType: .series)

            if isLiked{
                LikeFavCommonFunc.shareInstance.unlikePost(postID: showID, postType: postType, vc: self.vc) { isDone in
                    self.showData?.isLiked = false
                    self.showData?.likesCount! -= 1
                    self.setShowData()
                    self.vc.likeFavDelegate?.updateRows(index: indexSelected, type: .liked, isFav: nil, isLike: false, id: showID)
                    
                    if self.categoryID == 18{ // hindi
                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.hindi?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.showData?.hindi?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.showData?.hindi?[index].likesCount! -= 1
                            K.GVar.myListSoftReload = true
                        }
                    }else{ // english
                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.english?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.showData?.english?[index].isLiked = false
                            MyListDataTemp.shareInstance.favListingData?.showData?.english?[index].likesCount! -= 1
                            K.GVar.myListSoftReload = true
                        }
                    }
                }
            }else{
                LikeFavCommonFunc.shareInstance.likePost(postID: showID, postType: postType, vc: self.vc) { isDone in
                    self.showData?.isLiked = true
                    self.showData?.likesCount! += 1
                    self.setShowData()
                    self.vc.likeFavDelegate?.updateRows(index: indexSelected, type: .liked, isFav: nil, isLike: true, id: showID)
                    
                    if self.categoryID == 18{ // hindi
                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.hindi?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.showData?.hindi?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.showData?.hindi?[index].likesCount! += 1
                            K.GVar.myListSoftReload = true
                        }
                    }else{ // english
                        if let index = MyListDataTemp.shareInstance.favListingData?.showData?.english?.firstIndex(where: {$0.id == showID}){
                            MyListDataTemp.shareInstance.favListingData?.showData?.english?[index].isLiked = true
                            MyListDataTemp.shareInstance.favListingData?.showData?.english?[index].likesCount! += 1
                            K.GVar.myListSoftReload = true
                        }
                    }
                }
            }
        }
        
        vc.shareView.addTapGesture {
            if let showID = self.showData?.id,  let catID = self.categoryID{
                PersistentStorage.shared.addWebSeries(catID: catID, postID: showID, postType: .series)
            }

            if let name = URL(string: "https://apps.apple.com/in/app/woka/id6465305185"), !name.absoluteString.isEmpty {
              let objectsToShare = [name]
              let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
                self.vc.present(activityVC, animated: true, completion: nil)
            } else {
              // show alert for not available
            }
        }
    }
    
    func setShowData(){
        guard let showData else{return}
        vc.totalLikes.text = showData.likesCount?.toString() ?? "0"
        if let like = showData.isLiked{
            switch like{
            case true:
                vc.likeIcon.image = UIImage(systemName: "hand.thumbsup.fill")
                vc.likeLabel.text = "LIKED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            case false:
                vc.likeIcon.image = UIImage(systemName: "hand.thumbsup")
                vc.likeLabel.text = "LIKE".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            }
        }
        
        if let favourite = showData.markAsFavourite{
            if let categoryIds = showData.favouriteCategoryIDS?.rawValue { // if string, it means category is selected for multiple language
                let components = categoryIds.components(separatedBy: ",")
                if favourite == true && (components.first == categoryID?.toString() || components.last == categoryID?.toString()){
                    vc.addIcon.image = UIImage(systemName: "heart.fill")
                    vc.addLabel.text = "ADDED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }else{
                    vc.addIcon.image = UIImage(systemName: "heart")
                    vc.addLabel.text = "ADD".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                }
                return
            }
            
            if favourite == true && showData.favouriteCategoryIDS?.intValue == categoryID{
                vc.addIcon.image = UIImage(systemName: "heart.fill")
                vc.addLabel.text = "ADDED".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            }else{
                vc.addIcon.image = UIImage(systemName: "heart")
                vc.addLabel.text = "ADD".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            }
        }
    }
    
    func setupCell(){
        vc.categoryCV.register(UINib(nibName: K.CellIdentifier.WebSeries.seasonCategoryCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.WebSeries.seasonCategoryCell)
        vc.categoryCV.delegate = vc.self
        vc.categoryCV.dataSource = vc.self
        
        vc.episodeTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesEpisodeCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesEpisodeCell)
        vc.episodeTableView.delegate = vc.self
        vc.episodeTableView.dataSource = vc.self
        
        vc.teaserTableView.register(UINib(nibName: K.CellIdentifier.WebSeries.webSeriesEpisodeCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.WebSeries.webSeriesEpisodeCell)
        vc.teaserTableView.delegate = vc.self
        vc.teaserTableView.dataSource = vc.self
    }
    
    // MARK: - Api Calls

    func getSeasonListing(){
        Utilities.startProgressHUD()
        guard let watchShowID = showData?.id, let categoryID else{return}
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["watch_show_id" : watchShowID,
                                   "category_id" : categoryID]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.season_listing, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<SeasonListingDM>, 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.noDataStack.isHidden = false
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    self.vc.noDataStack.isHidden = true
                    self.vc.scrollView.isHidden = false
                    self.seasonListingData = data
                    episodeSelectedCateogory = seasonListingData.first?.id
                    setSeasonData()
                    
                    Utilities.startProgressHUD()
                    getSeasonEpisode()
                    getTeaserListing()
                    self.vc.categoryCV.reloadData()
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                self.vc.noDataStack.isHidden = false
                vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func setSeasonData(){
        guard let data = seasonListingData.filter({$0.id == episodeSelectedCateogory}).first else{return}
        vc.seasonImage.imageURL(data.thumbnailPath!, color: UIColor.appColor(.TextDarkBlue)!)
        
        if AuthFunc.shareInstance.getDefaultLanguage() == .english{
            let englishData = data.seasonMoreDetails?.filter({$0.languageMasterID == 1}).first
            vc.seasonTitle.text = (englishData?.title ?? "NA") + "\n" + (data.seasonNumber ?? "NA")
            self.vc.title = (englishData?.title ?? "Show")

            if let desc = englishData?.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                let sizeText = NSMutableAttributedString(attributedString: desc)
                sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                self.vc.seasonDesc.attributedText = sizeText
            }
        }else{
            let hindiData = data.seasonMoreDetails?.filter({$0.languageMasterID == 2}).first
            vc.seasonTitle.text = (hindiData?.title ?? "NA") + "\n" + (data.seasonNumber ?? "NA")
            self.vc.title = (hindiData?.title ?? "Show")

            if let desc = hindiData?.description?.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                let sizeText = NSMutableAttributedString(attributedString: desc)
                sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 15),color: UIColor.appColor(.TextDarkBlue)!)
                self.vc.seasonDesc.attributedText = sizeText
            }
        }
        
        vc.seasonDate.text = data.releaseYear?.toString()
        vc.seasonEpisodes.text = data.noOfEpisodes?.toString()
        vc.seasonMediaType.text = data.mediaType
    }
    
    func getSeasonEpisode(){
        
        guard let watchShowID = showData?.id, let episodeSelectedCateogory else{return}
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["watch_show_master_id" : watchShowID,
                                   "season_master_id" : episodeSelectedCateogory,
                                   "api_version" : "v2",
                                   "start" : pageNo,
                                   "limit": 10]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.episode_listing, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<EpisodeListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    if pageNo == 0 {
                        self.seasonEpisodeData.removeAll()
                    }
                    self.vc.episodeTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.episodeTableView.contentSize.height + 100
                    self.vc.episodeTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.episodeTableView.contentSize.height
//                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let dataCount = data.data?.totalRecords ,let data = data.data?.result else{return}
                    if pageNo == 0 {
                        self.seasonEpisodeData.removeAll()
                    }
                    self.seasonEpisodeData.append(contentsOf: data)
//                    self.seasonEpisodeData = self.seasonEpisodeData.filter {
//                        $0.episodeData != nil && !$0.episodeData!.isEmpty
//                    }
                    
                    
                    self.vc.loadMoreActivityIndicator.stopAnimating()
                    self.vc.loadMoreActivityIndicator.hidesWhenStopped = true
                    
                    if self.seasonEpisodeData.count == dataCount{
                        self.vc.loadMoreBtn.isHidden = true
                    }else{
                        self.vc.loadMoreBtn.isHidden = false
                    }
                    
                    if self.seasonEpisodeData.count == 0{
                        self.vc.episodeTitle.isHidden = true
                        self.vc.episodeTitle.text = ""
                    }else{
                        self.vc.episodeTitle.isHidden = false
                        self.vc.episodeTitle.text = "Episodes"
                    }
                    
                    self.vc.episodeTableView.reloadData()
                    self.vc.tableHeight.constant = self.vc.episodeTableView.contentSize.height + 100
                    self.vc.episodeTableView.layoutIfNeeded()
                    self.vc.tableHeight.constant = self.vc.episodeTableView.contentSize.height
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func getTeaserListing(){
        guard let watchShowID = showData?.id, let episodeSelectedCateogory else{return}
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["watch_show_master_id" : watchShowID,
                                   "season_master_id" : episodeSelectedCateogory]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.WebSeries.teaser_listing, method: .post,parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<TeaserDM>, 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.teaserData.removeAll()
                    self.reloadTeaserTable()
                    self.vc.teaserTitle.isHidden = true
//                    vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    self.teaserData.removeAll()
                    self.teaserData = data
                    self.reloadTeaserTable()
                    self.vc.teaserTitle.isHidden = false
                default:
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    private func reloadTeaserTable(){
        self.vc.teaserTableView.reloadData()
        self.vc.teaserTableHeight.constant = self.vc.teaserTableView.contentSize.height + 100
        self.vc.teaserTableView.layoutIfNeeded()
        self.vc.teaserTableHeight.constant = self.vc.teaserTableView.contentSize.height
    }
}
