//
//  MyListViewAllVC.swift
//  WOKA
//
//  Created by MacBook Pro on 08/08/24.
//

import UIKit

class MyListViewAllVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableHeight: NSLayoutConstraint!
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var loadMoreBtn: LocalisedElementsButton!
    @IBOutlet weak var loadMoreActivityIndicator: UIActivityIndicatorView!
    
    var vm = MyListViewAllVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
//        let color1 = #colorLiteral(red: 0, green: 0.4784313725, blue: 0.7529411765, alpha: 1)
//        let color2 = #colorLiteral(red: 0, green: 0.7529411765, blue: 0.7529411765, alpha: 1)
//        self.view.applyGradient(colors: [color1,color2], startPoint: .Point.left.point , endPoint: .Point.right.point)
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
        self.navigationController?.setColor(color: .black)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if K.GVar.reloadMyListAll != 0{ // 0 - null, 1 - add , 2- remove
            
            // first check if add or remove
            if K.GVar.reloadMyListAll == 1{
                switch vm.postType{
                case 1: // webseries
                    if vm.catID == "1"{ // english
                        if let englishData = vm.favListingData?.showData?.english, let firstIndex = englishData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                            
                        }else{
                            vm.pageNo = 0
                            vm.getFavouriteListing()
                        }
                    }else{// hindi
                        if let hindiData = vm.favListingData?.showData?.hindi, let firstIndex = hindiData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){                            
                        }else{
                            vm.pageNo = 0
                            vm.getFavouriteListing()
                        }
                    }
                case 6: // Games
                    if let gameData = vm.favListingData?.gameData{
                        
                    }
                case 7:
                    if let audioData = vm.favListingData?.audioData{
                        
                    }
                case 8: //KAraoke
                    if let karaokeData = vm.favListingData?.singKaraokeData{
                        
                    }
                default:
                    break
                }
            }else if K.GVar.reloadMyListAll == 2{
                switch vm.postType{
                case 1: // webseries
                    if vm.catID == "1"{ // english
                        if let englishData = vm.favListingData?.showData?.english, let firstIndex = englishData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                            vm.favListingData?.showData?.english?.remove(at: firstIndex)
                            self.tableView.reloadData()
                            self.tableHeight.constant = self.tableView.contentSize.height + 100
                            self.tableView.layoutIfNeeded()
                            let webSeriesCount = vm.favListingData?.showData?.english?.count ?? 0
                            self.tableHeight.constant = CGFloat(webSeriesCount * 230)
                        }else{
                            vm.pageNo = 0
                            vm.getFavouriteListing()
                        }
                    }else{// hindi
                        if let hindiData = vm.favListingData?.showData?.hindi, let firstIndex = hindiData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                            vm.favListingData?.showData?.hindi?.remove(at: firstIndex)
                            self.tableView.reloadData()
                            self.tableHeight.constant = self.tableView.contentSize.height + 100
                            self.tableView.layoutIfNeeded()
                            let webSeriesCount = vm.favListingData?.showData?.hindi?.count ?? 0
                            self.tableHeight.constant = CGFloat(webSeriesCount * 230)
                        }else{
                            vm.pageNo = 0
                            vm.getFavouriteListing()
                        }
                    }
                case 6: // Games
                    if let gameData = vm.favListingData?.gameData, let firstIndex = gameData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                        vm.favListingData?.gameData?.remove(at: firstIndex)
                        self.tableView.reloadData()
                        self.tableHeight.constant = self.tableView.contentSize.height + 100
                        self.tableView.layoutIfNeeded()
                        let webSeriesCount = vm.favListingData?.gameData?.count ?? 0
                        self.tableHeight.constant = CGFloat(webSeriesCount * 230)
                    }else{
                        vm.pageNo = 0
                        vm.getFavouriteListing()
                    }
                case 7:
                    if let audioData = vm.favListingData?.audioData,  let firstIndex = audioData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                        vm.favListingData?.audioData?.remove(at: firstIndex)
                        self.tableView.reloadData()
                        self.tableHeight.constant = self.tableView.contentSize.height + 100
                        self.tableView.layoutIfNeeded()
                        let webSeriesCount = vm.favListingData?.audioData?.count ?? 0
                        self.tableHeight.constant = CGFloat(webSeriesCount * 230)
                    }else{
                        vm.pageNo = 0
                        vm.getFavouriteListing()
                    }
                case 8: //KAraoke
                    if let karaokeData = vm.favListingData?.singKaraokeData,  let firstIndex = karaokeData.firstIndex(where: {$0.id == K.GVar.reloadMyListAllID}){
                        vm.favListingData?.singKaraokeData?.remove(at: firstIndex)
                        self.tableView.reloadData()
                        self.tableHeight.constant = self.tableView.contentSize.height + 100
                        self.tableView.layoutIfNeeded()
                        let webSeriesCount = vm.favListingData?.singKaraokeData?.count ?? 0
                        self.tableHeight.constant = CGFloat(webSeriesCount * 230)
                    }else{
                        vm.pageNo = 0
                        vm.getFavouriteListing()
                    }
                default:
                    break
                }
            }
            
            K.GVar.reloadMyListAll = 0 // reset to null
            K.GVar.reloadMyListAllID = 0
        }
        print("Appear")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.navigationController?.navigationBar.removeGradientBackground()

        // Customize the navigation bar's appearance
        self.navigationController?.setColor(color: .black)
    }

    @IBAction func loadMoreBtnTapped(_ sender: LocalisedElementsButton) {
        loadMoreBtn.isHidden = true
        vm.pageNo += 1
        loadMoreActivityIndicator.startAnimating()
        vm.getFavouriteListing()
    }
}

// MARK: - TableView DataSource , Delegates

extension MyListViewAllVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch vm.postType{
        case 1: // webSeries
            if vm.catID == "1"{
                return vm.favListingData?.showData?.english?.count ?? 0
            }else{
                return vm.favListingData?.showData?.hindi?.count ?? 0
            }
        case 6: // Games
            return vm.favListingData?.gameData?.count ?? 0
        case 7: // Audio
            return vm.favListingData?.audioData?.count ?? 0
        case 8: //KAraoke
            return vm.favListingData?.singKaraokeData?.count ?? 0
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch vm.postType{
        case 1: // webSeries
            if vm.catID == "1"{
                guard let showData = vm.favListingData?.showData?.english?[indexPath.row] else{return}

                if let showID = showData.id{
                    PersistentStorage.shared.addWebSeries(catID: 1, postID: showID, postType: .series)
                }
                
                let showDataModified = WebSeriesShowListDM.ShowDatum(id: showData.id, title: showData.title, description: showData.description, thumbnailPath: showData.thumbnailPath, showType: showData.showType, totalSeasons: showData.totalSeasons, totalEpisodes: showData.totalEpisodes, categoryMasterID: nil, ageRangeMasterID: nil, genderMasterID: showData.genderMasterID, contentMoreDetails: showData.contentMoreDetails, seasonData: nil, categoryData: nil, ageRangeData: nil, genderData: nil, markAsFavourite: showData.markAsFavourite, isLiked: showData.isLiked, likedCategoryIDS: nil, favouriteCategoryIDS: ValueWrapper.stringValue(showData.bookmarkCategoryIDS ?? "1") , likesCount: showData.likesCount, viewsCount: showData.viewsCount, bookmarkCount: showData.bookmarkCount)
                
                let sb = UIStoryboard(name: K.StoryBoard.webSeries, bundle: nil)
                let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.WebSeries.webSeriesSeasonVC) as! WebSeriesSeasonVC
                vcPush.vm.showData = showDataModified
                vcPush.vm.indexSelected = indexPath.row
                vcPush.vm.categoryID = 1
                self.navigationController?.pushViewController(vcPush, animated: true)
            }else{
                guard let showData = vm.favListingData?.showData?.hindi?[indexPath.row] else{return}

                if let showID = showData.id{
                    PersistentStorage.shared.addWebSeries(catID: 18, postID: showID, postType: .series)
                }
                
                let showDataModified = WebSeriesShowListDM.ShowDatum(id: showData.id, title: showData.title, description: showData.description, thumbnailPath: showData.thumbnailPath, showType: showData.showType, totalSeasons: showData.totalSeasons, totalEpisodes: showData.totalEpisodes, categoryMasterID: nil, ageRangeMasterID: nil, genderMasterID: showData.genderMasterID, contentMoreDetails: showData.contentMoreDetails, seasonData: nil, categoryData: nil, ageRangeData: nil, genderData: nil, markAsFavourite: showData.markAsFavourite, isLiked: showData.isLiked, likedCategoryIDS: nil, favouriteCategoryIDS: ValueWrapper.stringValue(showData.bookmarkCategoryIDS ?? "18") , likesCount: showData.likesCount, viewsCount: showData.viewsCount, bookmarkCount: showData.bookmarkCount)
                
                let sb = UIStoryboard(name: K.StoryBoard.webSeries, bundle: nil)
                let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.WebSeries.webSeriesSeasonVC) as! WebSeriesSeasonVC
                vcPush.vm.showData = showDataModified
                vcPush.vm.indexSelected = indexPath.row
                vcPush.vm.categoryID = 18
                self.navigationController?.pushViewController(vcPush, animated: true)
            }
            
        case 6://Games
            guard let gameData = vm.favListingData?.gameData?[indexPath.row] else{return}
            if let postID = gameData.id{
                PersistentStorage.shared.addGamesCount(postID: postID)
            }
            let sb = UIStoryboard(name: K.StoryBoard.Games, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Games.gamesDetailVC) as! GamesDetailVC
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            vcPush.gameData = gameData
            self.present(vcPush, animated: true)
        case 7: // audio books
            guard let audioData = vm.favListingData?.audioData?[indexPath.row] else{return}
            if let postID = audioData.id{
                PersistentStorage.shared.addAudioCount(postID: postID)
            }
            let sb = UIStoryboard(name: K.StoryBoard.audioBooks, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.AudioBooks.audioBookDetailsVC) as! AudioBookDetailsVC
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            vcPush.audioData = audioData
//            vcPush.delegate = self
            self.present(vcPush, animated: true)
        case 8: //KAraoke
            guard let karaokeData = vm.favListingData?.singKaraokeData?[indexPath.row] else{return}
            if let postID = karaokeData.id{
                PersistentStorage.shared.addKaraokeCount(postID: postID)
            }
            let sb = UIStoryboard(name: K.StoryBoard.Karaoke, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Karaoke.karaokeDetailsVC) as! KaraokeDetailsVC
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            vcPush.karaokeData = karaokeData

            self.present(vcPush, animated: true)
        default:
            break
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 230
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Home.myListViewAllCell) as! MyListViewAllCell
        switch vm.postType{
        case 1: // Webseries
            if vm.catID == "1"{ // eng
                if let webSeriesData = vm.favListingData?.showData?.english?[indexPath.row] {
                    cell.webSeriesData(data: webSeriesData)
                }
            }else{ // hin
                if let webSeriesData = vm.favListingData?.showData?.hindi?[indexPath.row] {
                    cell.webSeriesData(data: webSeriesData)
                }
            }
            
        case 6: // Games
            if let gameData = vm.favListingData?.gameData?[indexPath.row] {
                cell.gameData(data: gameData)
            }
        case 7:
            if let karaokeData = vm.favListingData?.audioData?[indexPath.row] {
                cell.audioData(data: karaokeData)
            }
        case 8: // Karaoke
            if let karaokeData = vm.favListingData?.singKaraokeData?[indexPath.row] {
                cell.setKaraokeData(data: karaokeData)
            }
        default:
            break
        }
        return cell
    }
}

