//
//  ShopListingVM.swift
//  WOKA
//
//  Created by MacBook Pro on 22/07/24.
//

import UIKit
import Alamofire

class ShopListingVM{
    
    weak var vc : ShopListingVC!
    var superCatData = [ShopSuperCategoryDM.ResultData]()
    var cartButton: UIBarButtonItem!

    func initView(){
        setupCell()
        addGradient()
        getSuperCategory()
        
        //check if cart is not fetched
        if !CartDataCache.isFetched{
            CartDataCache.shareInstance.getCartList(vc: self.vc) { [weak self] isDone in
                guard let self else{return}
                if isDone{
                    if let button = cartButton.customView as? UIButton {
                        BadgeBarBtn.shared.updateBadge(for: button, with: CartDataCache.cartListData.count.toString())
                    }
                }
            }
        }
        
        cartButton = BadgeBarBtn.shared.setupCartButton(target: self, action: #selector(self.cartButtonTapped))
        self.vc.navigationItem.rightBarButtonItem = cartButton
    }
    
    @objc func cartButtonTapped(){
        PersistentStorage.shared.addShopCount(postID: 0)
        if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

        let sb = UIStoryboard(name: K.StoryBoard.cart, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Cart.cartListVC) as! CartListVC
        self.vc.navigationController?.pushViewController(vcPush, animated: true)
    }
        
    func setupCell(){
        vc.tableView.register(UINib(nibName: K.CellIdentifier.Shop.shopListingCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.Shop.shopListingCell)
        vc.tableView.delegate = vc.self
        vc.tableView.dataSource = vc.self
    }
    
    func addGradient(){
        self.vc.title = "SHOP".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        let color1 = #colorLiteral(red: 0.6745098039, green: 0.6235294118, blue: 0.1725490196, alpha: 1)
        let color2 = #colorLiteral(red: 0.5450980392, green: 0.6745098039, blue: 0.1725490196, alpha: 1)
        
        vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    // MARK: - Get SuperCategory
    
    func getSuperCategory(){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["module_id" : "5"]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Shop.super_category_listing, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<ShopSuperCategoryDM>, 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.noDataStack.isHidden = false
                    vc.tableView.isHidden = true
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    vc.noDataStack.isHidden = true
                    vc.tableView.isHidden = false
                    
                    /*
                     MAke logic for ads
                     */
                    if let adsData = AuthFunc.shareInstance.adsData{
                        // check if ads data contains ad for webseries
                        if let shopSuperCatAd = adsData.result?.filter({$0.forPage == AdsEnum.shop_super_category.rawValue}).first, let bannerImage = shopSuperCatAd.bannerImage{
                            self.superCatData.append(ShopSuperCategoryDM.ResultData(id: shopSuperCatAd.id, superCategoryName: shopSuperCatAd.title, superCategoryThumbnail: bannerImage,isAD: true))
                        }
                    }
                    
                    self.superCatData.append(contentsOf: data)
                    self.vc.tableView.reloadData()
                default:
                    vc.noDataStack.isHidden = false
                    vc.tableView.isHidden = true
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                vc.noDataStack.isHidden = false
                vc.tableView.isHidden = true
                vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
}
