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

import UIKit
import Alamofire

class LoginVM{
    
    weak var vc : LoginVC!
    
    func initView(){
        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)
        
        vc.userNameTF.addRightButton(title: "", tintColor: UIColor.red, btnImage: UIImage(systemName: "exclamationmark.circle.fill"), target: self, action: #selector(validationIconTapped))
        vc.userNameTF.rightView?.isHidden = true
        
        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
        
        self.vc.view.addTapGesture {
            let errorView = errorViews.object(forKey: self.vc.userNameTF)
            if let errorView = errorView {
                errorView.isHidden = true
            }
        }
    }
    
    // Function to handle tap on validation icon
    @objc func validationIconTapped() {
        let errorView = errorViews.object(forKey: vc.userNameTF)
        if let errorView = errorView {
            errorView.isHidden.toggle()
        }
    }
    
    // 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!
        ]
        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 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()
                            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
                         */
                    }
                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(){
        let params: Parameters = [
            "username": vc.userNameTF.text!,
            "password": vc.passwordTF.text!
        ]
        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_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()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                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
            "one_signal_player_id": "Test",
            "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"]
        
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.guest_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()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2) {
                        let sb1 = UIStoryboard(name: "Home", bundle: nil)
                        let vc1 = sb1.instantiateViewController(withIdentifier: "SideMenu") as! SideMenuController
                        self.vc.navigationController?.pushViewController(vc1, animated: true)
                    }
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
}
