//
//  AppUpdateVC.swift
//  WOKA
//
//  Created by MacBook Pro on 20/08/24.
//

import UIKit
import Alamofire

class AppUpdateVC: UIViewController {

    @IBOutlet weak var updateBtn: LocalisedElementsButton!
    @IBOutlet weak var skipBtn: LocalisedElementsButton!
    
    var isForceUpdate = Bool()
    var forceUpdateVer = String()
    override func viewDidLoad() {
        super.viewDidLoad()
        handleViewUpdate()
    }
    
    func handleViewUpdate(){
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.6901960784, green: 0.2745098039, blue: 0.7568627451, alpha: 1)
        updateBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        updateBtn.roundCorner()
        
        skipBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        skipBtn.roundCorner()
        
        if isForceUpdate{
            skipBtn.isHidden = true
        }else{
            skipBtn.isHidden = false
        }
    }
    
    @IBAction func btnTapped(_ sender: LocalisedElementsButton) {
        if sender == updateBtn{
            print("Update")
            // take user to appstore
            redirectToAppStore()
        }else{
            //if user clicks skip update it to our user defaults
            UserDefaults.standard.set(forceUpdateVer, forKey: K.UserDefaultsStruct.appUpdateSkipVer)
//            getUserData()
            if AuthFunc.shareInstance.checkLogin(){
                getUserData()
            }else{
                //check if the static url data is fetched
                UIApplication.setRootView(LoginNavVC.instantiate(from: .AuthenticationSB))
            }
        }
    }
    
    func redirectToAppStore() {
        let appID = "6465305185" // Replace with your actual App Store ID
        let appStoreURL = "https://apps.apple.com/app/id\(appID)"
        
        if let url = URL(string: appStoreURL), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: { success in
                if success {
                    print("Redirected to the App Store.")
                } else {
                    print("Failed to open the App Store URL.")
                }
            })
        } else {
            print("Invalid App Store URL.")
        }
    }
    
    func getUserData(){
        /*
         If user is guest then dont do the nw call
         */
        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)
            UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
            return
        }


//        if AuthFunc.shareInstance.getUserType() == 3{
//            UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
//            return
//        }
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token": AuthFunc.shareInstance.getAccessToken()]
        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:
                    self.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1:
                    guard let data = data.data?.result else{
                        Utilities.dismissProgressHUD()
                        return
                    }
                    AuthFunc.shareInstance.userData = data
                    Utilities.dismissProgressHUD()
                    //check if the static url data is fetched
                    if AuthFunc.shareInstance.staticURLs == nil{
                        AuthFunc.shareInstance.getStaticURLs()
                    }
                    DispatchQueue.main.async {
                        UIApplication.setRootView(SideMenuController.instantiate(from: .Home))
                    }
                    print("User Token --> ", AuthFunc.shareInstance.getAccessToken())
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                guard let self else{return}
                self.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
}
