//
//  UserDetailsRegisterVC.swift
//  WOKA
//
//  Created by MacBook Pro on 29/04/24.
//

import UIKit

class UserDetailsRegisterVC : UIViewController{
    
    @IBOutlet weak var nextBtn: LocalisedElementsButton!
    @IBOutlet weak var enterNameTF: TextFieldShadow!
    @IBOutlet weak var enterUserNameTF: TextFieldShadow!
    @IBOutlet weak var enterPasswordTF: TextFieldShadow!
    @IBOutlet weak var dontSharePassLabel: LocalisedElementsLabel!
    
    @IBOutlet weak var viewTitleLabel: LocalisedElementsLabel!
    @IBOutlet weak var userNameTitleLabel: LocalisedElementsLabel!
    @IBOutlet weak var nameTitleLabel: LocalisedElementsLabel!
    @IBOutlet weak var passTitleLabel: LocalisedElementsLabel!
    
    var vm = UserDetailsRegisterVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
        self.navigationController?.setColor(color: .black)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
        
        enterNameTF.hideError()
        enterUserNameTF.hideError()
        
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
            self.navigationController?.popToViewController(of: EmailVC.self, animated: true)
        }
    }
    
    // MARK: - Button Tap Handler
    
    @IBAction func nextBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        guard let name = enterNameTF.text?.trimmingCharacters(in: .whitespaces) ,let userName = enterUserNameTF.text?.trimmingCharacters(in: .whitespaces) , let pass = enterPasswordTF.text?.trimmingCharacters(in: .whitespaces) else{return}
        
        /*
         Check for username, minimum 3 letters required
         */
        if userName.count == 0{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = K.ConstantString.enterUserName.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        if userName.count < 3{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = K.ConstantString.shortUsername.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Username".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        /*
         Check for name
         */
        if name.count == 0{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = K.ConstantString.enterName.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Name".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        if name.count < 2{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = "Name is too short.".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = "Name".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        /*
         Check for password
         */
        if pass.count < 6{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            
            vcPush.contentLabel = K.ConstantString.shortPass.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.mainTitleText = K.ConstantString.error.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        
        /*
         Check if the username exist or not
         */
        vm.checkUsernameExist { isDone in
            if isDone{
                /*
                 Initializing our local data store for user Register
                 */
                AuthFunc.shareInstance.regData.full_name = name
                AuthFunc.shareInstance.regData.username = userName
                AuthFunc.shareInstance.regData.password = pass
                
                let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.userIntrestVC) as! UserIntrestVC
                vc.vm.createChildAccount = self.vm.createChildAccount ?? false
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}

// MARK: - Textfield Delegate

extension UserDetailsRegisterVC : UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        switch textField{
        case enterNameTF:
            if !string.nameCharacterOnly(){return false}
            return ValidatorClass.sharedInstanec.limitCharacter(length: 50,textField, shouldChangeCharactersIn: range, replacementString: string)
        case enterUserNameTF:
            if !string.userName(){return false}
            return ValidatorClass.sharedInstanec.limitCharacter(length: 16,textField, shouldChangeCharactersIn: range, replacementString: string)
        case enterPasswordTF:
            let currentString = (textField.text ?? "") as NSString
            let newString = currentString.replacingCharacters(in: range, with: string)
            newString.count == 0 ? (textField.rightView?.isHidden = true) : (textField.rightView?.isHidden = false)
            return ValidatorClass.sharedInstanec.limitCharacter(length: 16,textField, shouldChangeCharactersIn: range, replacementString: string)
        default:
            return true
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        switch textField{
        case enterUserNameTF:
            enterNameTF.becomeFirstResponder()
        case enterNameTF:
            enterPasswordTF.becomeFirstResponder()
        case enterPasswordTF:
            enterPasswordTF.resignFirstResponder()
        default:
            break
        }
        return true
    }
    
}
