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

import UIKit
import AVFoundation
import Alamofire
import FirebaseAnalytics
import GoogleMobileAds

class SplashVM{
    
    weak var vc : SplashVC!
    var player: AVAudioPlayer?
    
    var banner1 = GADBannerView()
    var banner2 = GADBannerView()

    
    func initView(){
        
        if AuthFunc.shareInstance.staticURLs == nil{
            AuthFunc.shareInstance.getStaticURLs()
        }
        
        if AuthFunc.shareInstance.adsData == nil{
            AuthFunc.shareInstance.getAds()
        }
        vc.activityIndicator.hidesWhenStopped = true
        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)
        vc.hindiBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.englishBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.hindiBtn.roundCorner()
        vc.englishBtn.roundCorner()
        selectTheme()
        
        // check if user has selected the default language
        if let language = AuthFunc.shareInstance.getDefaultLanguage(){
            AuthFunc.shareInstance.languageSelected = language
        }else{
            AuthFunc.shareInstance.setDefaultLanguage(language: .english)
        }        
    }
    
    // Play initial sound
    func playSplashSound() {
        guard let path = Bundle.main.path(forResource: K.StaticFilesString.wokaSplashSound, ofType:"m4a") else {
            return }
        let url = URL(fileURLWithPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    func selectTheme(){
        let theme = UserDefaults.standard.string(forKey: K.UserDefaultsStruct.themeDefault)
        if theme != nil{
            (theme == ThemeSelect.theme1.rawValue) ? (AuthFunc.shareInstance.selectedTheme = .theme1) : (AuthFunc.shareInstance.selectedTheme = .theme2)
        }else{
            AuthFunc.shareInstance.selectedTheme = .theme1
        }
    }
    
    // MARK: - Get the user data if loginned

    func getUserData(){
        if AuthFunc.shareInstance.getUserType() == 3{
            //setusertype
            AuthFunc.shareInstance.userData = UserDataDM.ResultData(id: nil, 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)
            if AuthFunc.shareInstance.adsData == nil{
                AuthFunc.shareInstance.getAds()
            }
            if AuthFunc.shareInstance.staticURLs == nil{
                AuthFunc.shareInstance.getStaticURLs { isDone in
                    if isDone == true{
                        UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
                    }else{
                        self.vc.retryBtn.isHidden = false
                    }
                }
            }else{
                UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
            }
            return
        }

        /*
         If user is guest then dont do the nw call
         */
        if AuthFunc.shareInstance.getUserType() == 3{
            UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
            return
        }
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token": AuthFunc.shareInstance.getAccessToken()]
        startStopIndicator(start: true)
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.get_user_data, method: .get, headers: headers) { [weak self](result : Result<BaseResponseModel<UserDataDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{return}
                switch data.success{
                case 0:
                    startStopIndicator(start: false)
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    startStopIndicator(start: false,hide: true)
                    guard let data = data.data?.result else{return}
                    AuthFunc.shareInstance.userData = data
                    
                    //check if the static url data is fetched
                    if AuthFunc.shareInstance.staticURLs == nil{
                        AuthFunc.shareInstance.getStaticURLs()
                    }
                    if AuthFunc.shareInstance.adsData == nil{
                        AuthFunc.shareInstance.getAds()
                    }
                    
                    DispatchQueue.main.async {
                        UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
                    }
                    print("User Token --> ", AuthFunc.shareInstance.getAccessToken())
                default:
                    break
                }
            case .failure(let error):
                guard let self else{return}
                startStopIndicator(start: false)
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func getVersionHistory(){
        let newVersion = "25.1.7"
        let forceUpdateVersion = "25.1.7"
        let forceUpdate = false
        let currentAppVersion = Bundle.main.appVersionLong
        
        /*
         If user is guest then dont do the nw call
         */
        let params : Parameters = ["device" : "2"] //1-android , 2- iOS
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.version_history, method: .get,parameters: params) { [weak self](result : Result<BaseResponseModel<AppUpdateDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{return}
                switch data.success{
                case 0:
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    guard let data = data.data?.the0 else{return}
                    if newVersion.isVersion(greaterThan: currentAppVersion) {
                        // Case: New version is greater than the current version
                        print("New version is greater than current version.")
                        
                        /*
                         Check if user has skipped the force update version
                         */
                        let skippedVer = UserDefaults.standard.string(forKey: K.UserDefaultsStruct.appUpdateSkipVer)
                        if skippedVer == forceUpdateVersion{
                            // it means user has skipped this version.
                            vc.animateForward()
                            return
                        }
                        
                        // If ver is not skipped let user navigate to app update vc
                        if forceUpdate {
                            print("Force update required by the API.")
                            // nav user to force update screen
                            let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.appUpdateVC) as! AppUpdateVC
                            vcPush.forceUpdateVer = forceUpdateVersion
                            self.vc.navigationController?.pushViewController(vcPush, animated: true)
                        } else {
                            print("Update available, but not mandatory.")
                            // Optional update let user skip
                            let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.appUpdateVC) as! AppUpdateVC
                            vcPush.forceUpdateVer = forceUpdateVersion
                            self.vc.navigationController?.pushViewController(vcPush, animated: true)
                        }
                    } else {
                        // Case: Current version is equal to the new version
                        print("Current version is up-to-date.")
                        vc.animateForward()
                    }
                    
                    print("data:- ", data.forceUpdateVersion)
                default:
                    break
                }
            case .failure(let error):
                guard let self else{return}
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    
    // handling activity indicator
    func startStopIndicator(start : Bool , hide : Bool = false){
        if hide{
            vc.activityIndicator.stopAnimating()
            vc.activityIndicator.isHidden = true
            vc.retryBtn.isHidden = true
            return
        }
        if start{
            vc.activityIndicator.isHidden = false
            vc.activityIndicator.startAnimating()
            vc.retryBtn.isHidden = true
        }else{
            vc.activityIndicator.stopAnimating()
            vc.activityIndicator.isHidden = true
            vc.retryBtn.isHidden = false
        }
    }
}


extension String {
    func isVersion(greaterThan version: String) -> Bool {
        let versionComponents = self.split(separator: ".").compactMap { Int($0) }
        let comparisonComponents = version.split(separator: ".").compactMap { Int($0) }
        
        for (index, component) in versionComponents.enumerated() {
            if index < comparisonComponents.count {
                if component > comparisonComponents[index] {
                    return true
                } else if component < comparisonComponents[index] {
                    return false
                }
            } else {
                return true
            }
        }
        
        return versionComponents.count > comparisonComponents.count
    }
}
