//
//  OnBoardVM.swift
//  WOKA
//
//  Created by Bilal on 26/04/2024.
//

import UIKit
import Lottie
import Alamofire
import FirebaseAnalytics

class OnBoardVM{
    
    weak var vc : OnBoardVC!
    private var animationView: LottieAnimationView?

    var data : [CarouselData]?
    
    func initData(){
        //Animate background
        animateWokaLogo()
        
        //Play Sound globally
        playBackGroundAnimationJSON()

        //Gradient and round corner for button
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.4862745098, green: 0.1960784314, blue: 0.7019607843, alpha: 1)
        let color3 = #colorLiteral(red: 0.968627451, green: 0.7882352941, blue: 0.1294117647, alpha: 1)
        let color4 = #colorLiteral(red: 0.968627451, green: 0.4196078431, blue: 0.1098039216, alpha: 1)
        let color5 = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.231372549, alpha: 1)
        let color6 = #colorLiteral(red: 0.09803921569, green: 0.4392156863, blue: 0.4156862745, alpha: 1)
        vc.createAccountBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.loginBtn.applyGradient(colors: [color4, color3], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.loginAsGuestBtn.applyGradient(colors: [color6, color5], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        
        vc.createAccountBtn.roundCorner()
        vc.loginBtn.roundCorner()
        vc.loginAsGuestBtn.roundCorner()
        
        // Setting button text to localize
        vc.createAccountBtn.setTitle("CREATE YOUR ACCOUNT".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), for: .normal)
        vc.loginBtn.setTitle("LOGIN".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), for: .normal)
        vc.loginAsGuestBtn.setTitle("Continue as a Guest".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), for: .normal)
        
        // Init Collection Data
        vc.pageControl.numberOfPages = 3
        data = [CarouselData(title: "Watch, Listen & Play".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), desc: "LIVE TV, VIDEOS, GAMES, AND AUDIO BOOKS".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), image: "Slide1"),
                CarouselData(title: "Sing-Along and Shop".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), desc: "", image: "Slide2"),
                CarouselData(title: "Lets all go to WOKALAND".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), desc: "".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue), image: "Slide3")]
        
        //Setup CollectionView
        setupCell()

        //after all setup animate the bottom stack to appear
        UIView.animate(withDuration: 0.3, delay: 0.4, options: .transitionCrossDissolve, animations: {
            self.vc.mainStack.alpha = 1
        }, completion: nil)
    }
    
    func animateWokaLogo(){
        let topConstriant = CheckPhoneHomeBtnOrNotch.shareInstance.topConstriant()
        UIView.animate(withDuration: 0.6, animations: {
            
            self.vc.wokaLogoTopConstriant.constant = topConstriant

            // Inform the layout system to update
            self.vc.view.layoutIfNeeded()
            // Unhide the view with cross dissolve animation and delay
        })
    }
   
    func setupCell(){
        vc.carouselCV.register(UINib(nibName: K.CellIdentifier.OnBoarding.onBoardCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.OnBoarding.onBoardCell)
        vc.carouselCV.delegate = vc.self
        vc.carouselCV.dataSource = vc.self
    }
    
    // MARK: - Background animation

    func playBackGroundAnimationJSON(){
        
        animationView = .init(name: K.StaticFilesString.passingCloud)
        animationView!.frame = vc.viewLottie.bounds
        
        //Set animation content mode
        animationView!.contentMode = .scaleAspectFill
        
        //Set animation loop mode
        animationView!.loopMode = .loop
        animationView?.backgroundBehavior = .pauseAndRestore
        
        //Adjust animation speed
        animationView!.animationSpeed = 1
        
        vc.viewLottie.addSubview(animationView!)
        
        //Play animation
        animationView!.play()
    }
    
    func stopBackGroundAnimationJSON(){
        animationView?.pause()
    }
    
    func resumeBackGroundAnimationJSON(){
        animationView?.play()
    }
    
    // MARK: - Create Guest
    /*
     Guest Login
     */
    func guestLogin(){
        
        let params: Parameters = [
            "user_type": 3, // 1- kid , 2 - guardian , 3 - guest
            "one_signal_player_id": AuthFunc.shareInstance.getOneSignalID(),
            "language_id": AuthFunc.shareInstance.languageSelected == .english ? 1 : 2, //1-eng, 2 - hindi
            "device_type": 1 // 1- android , 2 - iOS
        ]
        let header : HTTPHeaders = ["device-id" : AuthFunc.shareInstance.getDeviceUUID(),
                                    "Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        animationView?.pause()
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.guest_login, method: .post ,parameters: params, headers: header) {(result : Result<BaseResponseModel<GuestDataDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let dataUser = data.data else{return}
                    
                    if let newGuest = dataUser.newGuest, newGuest == true{
                        //Fire Analytics
                        Analytics.logEvent(K.AnalyticsEventKeys.guest_login_iOS, parameters: nil)
                        Analytics.logEvent(K.AnalyticsEventKeys.new_user_iOS, parameters: nil)
                    }
                    
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2) {
                        let userDataConverted = UserDataDM.ResultData(id: nil, username: dataUser.username, fullname: dataUser.fullname, genderData: nil, birthdate: nil, email: nil, avtar: nil, avtarURL: nil, userType: "3", languageMasterID: nil, lastLogin: nil, rememberToken: nil, childDetail: nil, language: nil, alreadyLoggedIn: nil, isDeactive: nil)
                        AuthFunc.shareInstance.loginDefaults(data: userDataConverted)
                    }
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }

}
