import UIKit
import Async
import Toast_Swift
import WowonderMessengerSDK

class TwoFactorVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var twoFactorTextField: UITextField!
    @IBOutlet weak var confirmationCodeTextField: UITextField!
    @IBOutlet weak var confirmationCodeTextFieldView: UIView!
    @IBOutlet weak var saveButton: UIButton!
    
    // MARK: - Properties
    
    var typeString: String? = ""
    var isConfirmCode = false
    
    // 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)
    }
    
    // Two Factor Button Action
    @IBAction func twoFactorButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.twoFactorStatusAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.isConfirmCode {
            if self.confirmationCodeTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
                self.view.makeToast("Please enter code")
                return
            }
            self.verifyCode(code: self.confirmationCodeTextField.text ?? "", type: "verify")
        } else {
            if self.typeString == "on" {
                self.updateTwoFactorSendCode()
            } else {
                self.updateTwoFactor()
            }
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.textFieldSetUp()
        self.setData()
    }
    
    func textFieldSetUp() {
        self.confirmationCodeTextField.attributedPlaceholder = NSAttributedString(
            string: "Confirmation Code",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.confirmationCodeTextField.delegate = self
    }
    
    func setData() {
        if AppInstance.instance.userProfile?.two_factor == "0" {
            self.typeString = "off"
            self.twoFactorTextField.text = "Disable"
        } else {
            self.typeString = "on"
            self.twoFactorTextField.text = "Enable"
        }
    }
    
    private func updateTwoFactor() {
        if Connectivity.isConnectedToNetwork() {
            let type = self.typeString ?? ""
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                SettingsManager.instance.updateTwoStepVerification(session_Token: sessionToken, type: "off") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(success?.message ?? "")
                                AppInstance.instance.fetchUserProfile()
                                self.navigationController?.popViewController(animated: true)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                                print("error = \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
    private func updateTwoFactorSendCode() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                TwoFactorManager.instance.updateTwoFactor(session_Token: sessionToken) { (success, sessionError, serverError, error) in
                    if success != nil{
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(success?.message ?? "")
                                self.isConfirmCode = true
                                self.confirmationCodeTextFieldView.isHidden = false
                                self.saveButton.setTitle("Send", for: .normal)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                                print("error = \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
    private func verifyCode(code: String, type: String) {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                TwoFactorManager.instance.updateVerifyTwoFactor(session_Token: sessionToken, code: code, Type: type) { (success, sessionError,serverError, error) in
                    if success != nil{
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(success?.message ?? "")
                                self.dismiss(animated: true) {
                                    AppInstance.instance.fetchUserProfile()
                                    self.isConfirmCode = false
                                    self.confirmationCodeTextFieldView.isHidden = true
                                    self.saveButton.setTitle("Save", for: .normal)
                                    self.navigationController?.popViewController(animated: true)
                                }
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text)
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                            }
                        }
                    }else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                                print("error = \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: TwoFactorAuthDelegate Methods
extension TwoFactorVC: TwoFactorStatusAlertVCDelegate {
    
    func getTwoFactorStatusString(type: String) {
        if type == "on" {
            self.twoFactorTextField.text = "Enable"
        } else {
            self.twoFactorTextField.text = "Disable"
            self.confirmationCodeTextFieldView.isHidden = true
            self.saveButton.setTitle("Save", for: .normal)
            self.isConfirmCode = false
        }
        self.typeString = type
    }
    
}

// MARK: UITextFieldDelegate Methods
extension TwoFactorVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case confirmationCodeTextField:
            self.confirmationCodeTextFieldView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case confirmationCodeTextField:
            self.confirmationCodeTextFieldView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}
