import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift

class ChangePasswordVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var currentPasswordTextField: UITextField!
    @IBOutlet weak var currentPasswordTextFieldView: UIView!
    @IBOutlet weak var newPasswordTextField: UITextField!
    @IBOutlet weak var newPasswordTextFieldView: UIView!
    @IBOutlet weak var repeatPasswordTextField: UITextField!
    @IBOutlet weak var repeatPasswordTextFieldView: UIView!
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.currentPasswordTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            print("Please enter current password.")
            self.view.makeToast("Please enter current password.")
            return
        }
        if self.newPasswordTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            print("Please enter New Password.")
            self.view.makeToast("Please enter New Password.")
            return
        }
        if self.repeatPasswordTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            print("Please enter confirm password.")
            self.view.makeToast("Please enter confirm password.")
            return
        }
        if self.currentPasswordTextField.text != self.repeatPasswordTextField.text {
            print("Password does not match. Try again!")
            self.view.makeToast("Password does not match. Try again!")
            return
        }
        self.updatePassword()
    }
    
    // Reset Password Button Action
    @IBAction func resetPasswordButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.main.forgetPasswordVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.textFieldSetUp()
    }
    
    func textFieldSetUp() {
        self.currentPasswordTextField.attributedPlaceholder = NSAttributedString(
            string: "Current Password",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.currentPasswordTextField.delegate = self
        self.newPasswordTextField.attributedPlaceholder = NSAttributedString(
            string: "New Password",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.newPasswordTextField.delegate = self
        self.repeatPasswordTextField.attributedPlaceholder = NSAttributedString(
            string: "Repeat Password",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.repeatPasswordTextField.delegate = self
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension ChangePasswordVC {
    
    private func updatePassword() {
        let sessionToken = AppInstance.instance.sessionId ?? ""
        let currentPassword = self.currentPasswordTextField.text ?? ""
        let newPassword = self.newPasswordTextField.text ?? ""
        Async.background {
            SettingsManager.instance.updatePassword(session_Token: sessionToken, currentPassword: currentPassword, newPassword: newPassword, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("success = \(success?.message ?? "")")
                            self.view.makeToast(success?.message)
                            AppInstance.instance.fetchUserProfile()
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            self.view.makeToast(sessionError?.errors?.error_text ?? "")
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                            self.view.makeToast(serverError?.errors?.error_text ?? "")
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            print("error = \(error?.localizedDescription ?? "")")
                            self.view.makeToast(error?.localizedDescription ?? "")
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: UITextFieldDelegate Methods
extension ChangePasswordVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case currentPasswordTextField:
            self.currentPasswordTextFieldView.borderColorV = .accent
        case newPasswordTextField:
            self.newPasswordTextFieldView.borderColorV = .accent
        case repeatPasswordTextField:
            self.repeatPasswordTextFieldView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case currentPasswordTextField:
            self.currentPasswordTextFieldView.borderColorV = .color_divider
        case newPasswordTextField:
            self.newPasswordTextFieldView.borderColorV = .color_divider
        case repeatPasswordTextField:
            self.repeatPasswordTextFieldView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}
