//
//  SplashVC.swift
//  WOKA
//
//  Created by MacBook Pro on 25/04/24.
//

import UIKit
import Lottie
import OneSignalFramework
import GoogleMobileAds

class SplashVC: UIViewController {
    
    @IBOutlet weak var wokaLogo: UIImageView!
    @IBOutlet weak var hindiBtn: UIButton!
    @IBOutlet weak var englishBtn: UIButton!
    @IBOutlet weak var languageBtnStack: UIStackView!
    @IBOutlet weak var wokaOriginY: NSLayoutConstraint!
    
    @IBOutlet weak var retryBtn: UIButton!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    
    @IBOutlet weak var adBanner1: UIView!
    @IBOutlet weak var adBanner2: UIView!
    
    var vm = SplashVM()
    
    // MARK: - View Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        /*
         Show google ads with dispatch queue.
         */
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
            guard let self else{return}
            AdReusable.sharedInstance.setupBannerAd(bannerView: vm.banner1, in: adBanner1, adUnitID: K.GoogleAdIDs.splashBanner1, viewController: self)
            AdReusable.sharedInstance.setupBannerAd(bannerView: vm.banner2, in: adBanner2, adUnitID: K.GoogleAdIDs.splashBanner2, viewController: self)
        })
        
        
        vm.vc = self
        vm.playSplashSound()
        animateImageScale()
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
        
        print("OneSignalID:- ", OneSignal.User.pushSubscription.id ?? "NIL")
    }
    
    @IBAction func languageBtnTapped(_ sender: UIButton) {
        PersistentStorage.shared.addOthersCount()
        
        switch sender{
        case hindiBtn:
            UserDefaults.standard.setValue(LocalizedEnum.hindi.rawValue, forKey: K.UserDefaultsStruct.defaultLanguage)
            AuthFunc.shareInstance.languageSelected = .hindi
        case englishBtn:
            UserDefaults.standard.setValue(LocalizedEnum.english.rawValue, forKey: K.UserDefaultsStruct.defaultLanguage)
            AuthFunc.shareInstance.languageSelected = .english
        default:
            UserDefaults.standard.setValue(LocalizedEnum.english.rawValue, forKey: K.UserDefaultsStruct.defaultLanguage)
            AuthFunc.shareInstance.languageSelected = .english
        }
        
        let sb = UIStoryboard(name: K.StoryBoard.main, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.OnBoarding.onBoardVC) as! OnBoardVC
        
        // Create a CATransition instance
        let transition = CATransition()
        transition.duration = 0.3 // Set the duration of the animation
        transition.type = CATransitionType.fade // Set the type of animation to fade

        // Get the navigation controller
        guard let navigationController = navigationController else { return }

        // Perform the push animation with the custom transition
        navigationController.view.layer.add(transition, forKey: nil)
        navigationController.pushViewController(vc, animated: false)
    }
    
    @IBAction func retryBtnTapped(_ sender: UIButton) {
        if AuthFunc.shareInstance.getUserType() == 3{
            vm.startStopIndicator(start: true)
            if AuthFunc.shareInstance.staticURLs == nil{
                AuthFunc.shareInstance.getStaticURLs { [weak self] isDone in
                    guard let self else{return}
                    vm.startStopIndicator(start: false)
                    if isDone == true{
                        UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
                    }else{
                        self.retryBtn.isHidden = false
                    }
                }
            }else{
                vm.startStopIndicator(start: false)
                UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
            }
        }else{
            vm.getUserData()
        }
    }
    
    func animateImageScale() {
        UIView.animate(withDuration: 3.0, delay: 0, options: [], animations: {
            self.wokaLogo.transform = CGAffineTransform(scaleX: 1.8, y: 1.8)
        }, completion: nil)
        
//        let newConstant = wokaOriginY.constant - 50

        Timer.scheduledTimer(withTimeInterval: 6, repeats: false) { [weak self] _ in
            guard let self else{return}
            /*
             If user is loggined no need to shift the woka logo upside to new constant.
             Directly Navigate user to home
            */
//            vm.getVersionHistory()
            animateForward()
        }
    }
    
    func animateForward(){
        if AuthFunc.shareInstance.checkLogin(){
            vm.getUserData()
            return
        }else{
            //check if the static url data is fetched
            if AuthFunc.shareInstance.staticURLs == nil{
                AuthFunc.shareInstance.getStaticURLs()
            }
        }
        UIView.animate(withDuration: 0.5, animations: { [weak self] in
            guard let self else{return}
            // Update the constant value of the top constraint
            self.wokaOriginY.constant = wokaOriginY.constant - 50
            // Inform the layout system to update
            self.view.layoutIfNeeded()
        }) { _ in
            if !AuthFunc.shareInstance.checkLogin(){
                UIView.animate(withDuration: 0.3, delay: 0,options : [.transitionCrossDissolve],animations: {
                    // Set the isHidden property of the view
                    self.languageBtnStack.isHidden = false
                }) {_ in
                    // Inform the stack view to update its layout
                    self.languageBtnStack.layoutIfNeeded()
                }
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        vm.initView()
    }
    
}


// MARK: - Google Ad Banner Delegate

extension SplashVC : GADBannerViewDelegate{
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("bannerViewDidReceiveAd")
        bannerView.alpha = 0
        bannerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        UIView.animate(withDuration: 0.5, animations: {
            bannerView.alpha = 1
        })
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
        print("bannerViewDidRecordImpression")
    }
    
    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillPresentScreen")
    }
    
    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewWillDIsmissScreen")
    }
    
    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
        print("bannerViewDidDismissScreen")
    }
}


