//
//  ResetPassUserNameVM.swift
//  WOKA
//
//  Created by Bilal on 10/05/2024.
//

import UIKit
import Alamofire

class ResetPassUserNameVM{

    weak var vc : ResetPassUserNameVC!
    
    func initView(){
        vc.usernameTF.roundCorner()
        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)
        vc.nextBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.nextBtn.roundCorner()
        
        vc.usernameTF.placeholder = "Please enter you username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vc.usernameTF.delegate = self.vc
        
        //Adding error view to the name tf
        vc.usernameTF.addRightButton(title: "", tintColor: UIColor.red, btnImage: UIImage(systemName: "exclamationmark.circle.fill"), target: self, action: #selector(errorUserName))
        vc.usernameTF.rightView?.isHidden = true
    }
    
    @objc func errorUserName(){
        let errorView = errorViews.object(forKey: vc.usernameTF)
        if let errorView = errorView {
            errorView.isHidden.toggle()
        }
    }
    
    // MARK: - Send OTP via username
    
    func sendOtpToUserName(){
        let params : Parameters = ["username" : vc.usernameTF.text!]
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Auth.forgot_password_send_otp, method: .post, parameters: params,headers: headers) {(result : Result<BaseResponseModel<ForgotPassDM>, 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 sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.oTPVC) as! OTPVC
                        vc.vm.userName = self.vc.usernameTF.text!
                        self.vc.navigationController?.pushViewController(vc, animated: true)
                    }
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
            }
        }
    }
}
