//
//  LoginVM.swift
//  WOKA
//
//  Created by Bilal on 03/05/2024.
//

import UIKit
import Alamofire
import FirebaseAnalytics

class LoginVM{
    
    weak var vc : LoginVC!
    
    func initView(){
        self.vc.title = ""
        vc.passwordTF.delegate = self.vc
        vc.userNameTF.delegate = self.vc
        vc.passwordTF.placeholder = "Enter your password".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vc.userNameTF.placeholder = "Enter your username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        
        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)
        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)
        vc.createAccountBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.createAccountBtn.roundCorner()
        
        vc.loginBtn.applyGradient(colors: [color4, color3], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.loginBtn.roundCorner()
        
        vc.passwordTF.roundCorner()
        vc.userNameTF.roundCorner()
        vc.passwordTF.enablePasswordToggle()
        vc.passwordTF.rightView?.isHidden = true
    }
    
    // Function to handle tap on Password Toggle icon
    @objc func passwordIconTapped() {
        vc.passwordTF.isSelected.toggle()
        vc.passwordTF.isSecureTextEntry.toggle()
    }
    
    /*
     After all checks do the api call
     */
    func loginUser(){
        let params: Parameters = [
            "username": vc.userNameTF.text!,
            "password": vc.passwordTF.text!,
            "one_signal_player_id": AuthFunc.shareInstance.getOneSignalID()
        ]
        let header : HTTPHeaders = ["device-id" : AuthFunc.shareInstance.getDeviceUUID(),
                                    "Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.login, method: .post ,parameters: params, headers: header) {(result : Result<BaseResponseModel<UserDataDM>, 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 dataResult = data.data?.result, let loginStatus = dataResult.alreadyLoggedIn else{return}
                    if let deactivated = dataResult.isDeactive , deactivated == true{
                        let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
                        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.yesNoAlertVC) as! YesNoAlertVC
                        vcPush.mainTitleText = "Activate WOKA Account"
                        vcPush.contentLabel = "Would you like to reactivate your account?"
                        vcPush.onDoneBlock = { mode in
                            switch mode{
                            case .yes:
                                //If user clicked to proceed on login. Call the api.
                                self.proceedLogin(activate: true)
                            case .no:
                                print("no")
                            }
                        }
                        vcPush.modalPresentationStyle = .overCurrentContext
                        vcPush.modalTransitionStyle = .crossDissolve
                        self.vc.present(vcPush, animated: true)
                        return
                    }
                    if loginStatus == true{ // user is already loginned in other device
                        let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
                        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.yesNoAlertVC) as! YesNoAlertVC
                        vcPush.contentLabel = data.message ?? K.ConstantString.unRecognised
                        vcPush.onDoneBlock = { mode in
                            switch mode{
                            case .yes:
                                //If user clicked to proceed on login. Call the api.
                                self.proceedLogin(activate: false)
                            case .no:
                                print("no")
                            }
                        }
                        vcPush.modalPresentationStyle = .overCurrentContext
                        vcPush.modalTransitionStyle = .crossDissolve
                        self.vc.present(vcPush, animated: true)
                    }else{ // fresh login
                        /*
                         if user is not logined on other device directly nav him to home
                         */
                        self.vc.toast(msg: data.message ?? K.ConstantString.unRecognised, time: 2) {
                            AuthFunc.shareInstance.loginDefaults(data: dataResult)
                        }
                    }
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
    
    /*
     After all checks do the api call
     */
    func proceedLogin(activate : Bool){
        let params: Parameters = [
            "username": vc.userNameTF.text!,
            "password": vc.passwordTF.text!,
            "one_signal_player_id": AuthFunc.shareInstance.getOneSignalID(),
            "is_activate" : activate ? "1" : "0" // if activate send 1
        ]
        let header : HTTPHeaders = ["device-id" : AuthFunc.shareInstance.getDeviceUUID(),
                                    "one_signal_player_id": AuthFunc.shareInstance.getOneSignalID(),
                                    "Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.login_proceed, method: .post ,parameters: params, headers: header) {(result : Result<BaseResponseModel<UserDataDM>, 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 dataResult = data.data?.result else{return}
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2) {
                        AuthFunc.shareInstance.loginDefaults(data: dataResult)
                    }
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
    
    /*
     Guest Login
     */
    func guestLogin(){
        let params: Parameters = [
            "user_type": 3, // 1- kid , 2 - guardian , 3 - guest
            "language_id": AuthFunc.shareInstance.languageSelected == .english ? 1 : 2, //1-eng, 2 - hindi
            "one_signal_player_id": AuthFunc.shareInstance.getOneSignalID(),
            "device_type": 1 // 1- android , 2 - iOS
        ]
        let header : HTTPHeaders = ["device-id" : AuthFunc.shareInstance.getDeviceUUID(),
                                    "Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        
        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 newUser = dataUser.newGuest, newUser == true{ // if guest is new fire the analytic event
                        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)
            }
        }
    }
}
