//
//  UserNotificationVM.swift
//  WOKA
//
//  Created by MacBook Pro on 05/08/24.
//

import UIKit
import Alamofire
import GoogleMobileAds

class UserNotificationVM{
    
    weak var vc : UserNotificationVC!
    var userNotification = [UserNotificationDM]()
    let refreshControl = UIRefreshControl()
    let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
    var bottomBanner = GADBannerView()

    func initView(){
        let color1 = #colorLiteral(red: 0.05490196078, green: 0.01176470588, blue: 0.3882352941, alpha: 1)
        let color2 = #colorLiteral(red: 0.2041364683, green: 0.156624428, blue: 0.5904380268, alpha: 1)
        self.vc.view.applyMultiGradient(colors: [color1, color2,color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        self.vc.title = "NOTIFICATIONS"
        setupCell()
        Utilities.startProgressHUD()
        getUserNotification()
        
        //Adding pull to Refresh
        refreshControl.attributedTitle = NSAttributedString(string: "Refreshing...",attributes: [.foregroundColor: UIColor.white])
        refreshControl.tintColor = .white
        refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        vc.tableView.addSubview(refreshControl)
        
        checkAds()
    }
    
    func setupCell(){
        vc.tableView.register(UINib(nibName: K.CellIdentifier.Home.userNotificationCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.Home.userNotificationCell)
        vc.tableView.delegate = vc.self
        vc.tableView.dataSource = vc.self
    }
    
    // MARK: - Adss check
    
    func checkAds(){
        /*
         First check if webSeries ad is present via slug, then check for Local Ads, if not then check google ads.
         */
        if let adsData = AuthFunc.shareInstance.adsData, let notificatonAd = adsData.result?.filter({$0.slug == AdsEnum.myList.rawValue}).first{
            
            // check if ads data contains LocalAD for webseries
            if let advertisement = notificatonAd.advertisement,let bannerImage = advertisement.bannerImage{
                let imageView = UIImageView()
                
                imageView.imageURL(bannerImage, color: .textDarkBlue,type: .ads) { [weak self] isDone in
                    guard let self else{return}
                    // if image gives error hide the ad banner
                    if isDone == false{
                        vc.adView.isHidden = true
                    }else{
                        let height = UIScreen.main.bounds.width * 0.192
                        vc.adViewHeight.constant = height
                        vc.adView.alpha = 0
                        vc.adView.isHidden = false
                        // Set the image you want to display
                        imageView.imageURL(bannerImage, color: .white)
                        
                        // Enable auto-layout
                        imageView.translatesAutoresizingMaskIntoConstraints = false
                        
                        // Add the UIImageView to the view
                        vc.adView.addSubview(imageView)
                        
                        // Set UIImageView to match the size of the parent UIView
                        NSLayoutConstraint.activate([
                            imageView.leadingAnchor.constraint(equalTo: vc.adView.leadingAnchor),
                            imageView.trailingAnchor.constraint(equalTo: vc.adView.trailingAnchor),
                            imageView.topAnchor.constraint(equalTo: vc.adView.topAnchor),
                            imageView.bottomAnchor.constraint(equalTo: vc.adView.bottomAnchor)
                        ])
                        imageView.contentMode = .scaleAspectFit
                        UIView.animate(withDuration: 0.2, animations: { [weak self] in
                            guard let self else{return}
                            vc.adView.alpha = 1
                        })
                        
                        vc.adView.addTapGesture {
                            if let adID = notificatonAd.id{
                                PersistentStorage.shared.addAdsCount(adID: adID ,clicks: 1)
                            }
                            if let adLink = notificatonAd.advertisement?.adLink ,let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
                                UIApplication.shared.open(url)
                            }
                        }
                    }
                }
            }else if notificatonAd.googleAd != nil{
                /*
                 Show google ads with dispatch queue.
                 */
                //setup google banner ads.
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
                    AdReusable.sharedInstance.setupBannerAd(bannerView: self.bottomBanner, in: self.vc.adView, adUnitID: K.GoogleAdIDs.myListNotifications, viewController: self.vc, height: 6,width: 0)
                })
            }
        }
    }

    
    // MARK: - Pull to refresh

    @objc func refresh(_ sender: AnyObject) {
//        CommonNwCall.shareInstance.getUserNotification(vc: self,isRefreshing: true) { [weak self] isDone in
//            guard let self else{return}
//            feedbackGenerator.impactOccurred()
//            tableView.reloadData()
//            refreshControl.endRefreshing()
//        }
        getUserNotification()
        refreshControl.beginRefreshing()
    }
    
    // MARK: - Get Notifications
    
    func getUserNotification(){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Home.get_user_notifications, method: .get,headers : headers) { [weak self](result : Result<BaseResponseModel<[UserNotificationDM]>, NetworkManager.APIError>) in
            guard let self else{return}
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                    self.vc.noDataStack.isHidden = false
                    self.vc.tableView.isHidden = true
                    refreshControl.endRefreshing()
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data else{
                        self.vc.noDataStack.isHidden = false
                        return
                    }
                    self.userNotification.removeAll()
                    self.userNotification.append(contentsOf: data)
                    feedbackGenerator.impactOccurred()
                    self.vc.tableView.reloadData()
                    if data.count == 0{
                        self.vc.noDataStack.isHidden = false
                    }else{
                        self.vc.noDataStack.isHidden = true
                    }
                    self.vc.tableView.isHidden = false
                    refreshControl.endRefreshing()
                default:
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 2)
                    Utilities.dismissProgressHUD()
                    refreshControl.endRefreshing()
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                refreshControl.endRefreshing()
                vc.toast(msg: error.localizedDescription , time: 2)
                self.vc.noDataStack.isHidden = false
                self.vc.tableView.isHidden = true
            }
        }
    }

}
