"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ResetPasswordBox = void 0;
var _react = _interopRequireWildcard(require("react"));
var _message = _interopRequireDefault(require("../message"));
var _jquery = _interopRequireDefault(require("jquery"));
var _userContext = require("../../../context/user/userContext");
var _commonService = require("./../../../services/commonService");
var _wrapperService = require("../../../services/wrapperService");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const ResetPasswordBox = props => {
  const {
    state
  } = (0, _react.useContext)(_userContext.UserContext);
  const [showError, setShowError] = (0, _react.useState)(false);
  const [processing, setProcessing] = (0, _react.useState)(false);
  const [errorMessage, setErrorMessage] = (0, _react.useState)(null);
  const [showPassword, setShowPassword] = (0, _react.useState)(false);
  //const prefix = "";
  const prefix = "/" + (0, _wrapperService.getSubDomainName)();
  const imagePath = prefix + "/images/carousel-dot.svg";
  const addRemoveBodyOverFlowClass = mode => {
    const body = (0, _jquery.default)(document.body);
    const cls = "overflow-hidden";
    if (mode === true) {
      if (body.hasClass(cls) === false) {
        body.addClass(cls);
      }
    } else {
      body.removeClass(cls);
    }
  };
  const modalWrapperResetPasswordClassName = "modal-wrapper.reset-password";
  const errorMessageClassName = "error-message";
  let errorField = "." + modalWrapperResetPasswordClassName + " ";
  errorField += "." + errorMessageClassName;
  const selectors = {
    FormBlockWrapper: ".form-block-wrapper",
    PasswordField: ".password-field",
    ConfirmPasswordField: ".confirm-password-field",
    ShowPasswordCheckbox: "#showPasswordCheckbox",
    ResetPasswordButton: ".reset-password-button",
    Form: "#email-form",
    ErrorField: errorField,
    PasswordStrengthField: ".password-strength"
  };
  const triState = {
    Valid: 0,
    Invalid: 1,
    Empty: 2
  };
  const cSS = {
    LI: {
      Valid: "valid",
      Invalid: "invalid"
    },
    IMG: {
      Valid: "valid-checkmark",
      Invalid: "invalid-checkmark",
      None: "password-strength-bullet-point"
    }
  };
  const handleChange = (element1, element2) => {
    const passwordValue = (0, _jquery.default)(element1).val();
    const confirmPasswordValue = (0, _jquery.default)(element2).val();
    const validateLength = () => {
      if (passwordValue.length === 0) {
        return triState.Empty;
      }
      if (passwordValue.length >= 8 && passwordValue.length <= 12) {
        return triState.Valid;
      }
      return triState.Invalid;
    };
    const validateNumber = () => {
      let stateValue = triState.Empty;
      const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
      if (passwordValue.length > 0) {
        stateValue = triState.Invalid;
        for (let c = 0; c < arr.length; c++) {
          if (passwordValue.includes(arr[c].toString())) {
            stateValue = triState.Valid;
            break;
          }
        }
      }
      return stateValue;
    };
    const validateSpecialCharacter = () => {
      let stateValue = triState.Empty;
      const arr = ["@", "#", "$", "^", "~", "`", "!", "%", "&", "*", "(", ")", "{", "}", "[", "]", ":", ";", '"', "<", ">", "?", "/", "|", "\\", "+", "=", "-", "_", "'", ",", "."];
      if (passwordValue.length > 0) {
        stateValue = triState.Invalid;
        for (let c = 0; c < arr.length; c++) {
          if (passwordValue.includes(arr[c].toString())) {
            stateValue = triState.Valid;
            break;
          }
        }
      }
      return stateValue;
    };
    const validateRestrictedCharacter = () => {
      return triState.Valid;
    };
    const validateUpperLowerCaseCharacters = () => {
      let stateValue1 = triState.Empty;
      let stateValue2 = triState.Empty;
      const arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
      if (passwordValue.length > 0) {
        stateValue1 = triState.Invalid;
        stateValue2 = triState.Invalid;
        for (let c = 0; c < arr.length; c++) {
          if (passwordValue.includes(arr[c].toString())) {
            stateValue1 = triState.Valid;
            break;
          }
        }
        for (let c = 0; c < arr.length; c++) {
          if (passwordValue.includes(arr[c].toString().toLowerCase())) {
            stateValue2 = triState.Valid;
            break;
          }
        }
      }
      if (stateValue1 === stateValue2) {
        return stateValue1;
      }
      return triState.Invalid;
    };
    const validateMatch = () => {
      if (passwordValue.length > 0) {
        if (passwordValue !== confirmPasswordValue) {
          return triState.Invalid;
        }
        return triState.Valid;
      }
      return triState.Empty;
    };
    const lengthValidationResult = validateLength();
    const numberValidationResult = validateNumber();
    const specialCharacterValidationResult = validateSpecialCharacter();
    const restrictedCharacterValidationResult = validateRestrictedCharacter();
    const upperLowerCaseCharactersValidationResult = validateUpperLowerCaseCharacters();
    const matchResult = validateMatch();
    let parent = (0, _jquery.default)(selectors.PasswordStrengthField);
    const liSelectors = ["chars", "letters", "special", "restricted", "digits", "match"];
    const values = [lengthValidationResult, upperLowerCaseCharactersValidationResult, specialCharacterValidationResult, restrictedCharacterValidationResult, numberValidationResult, matchResult];
    let results = [];
    for (let s = 0; s < liSelectors.length; s++) {
      let sSelector = (0, _jquery.default)(parent).find("li." + liSelectors[s]);
      let img = sSelector.find("img");
      sSelector.removeClass(cSS.LI.Valid).removeClass(cSS.LI.Invalid);
      img.removeClass(cSS.IMG.Valid).removeClass(cSS.IMG.Invalid).removeClass(cSS.IMG.None).attr("src", "");
      const result = values[s];
      results.push(result);
      switch (result) {
        case triState.Valid:
          {
            sSelector.addClass(cSS.LI.Valid);
            img.addClass(cSS.IMG.Valid);
            img.attr("src", prefix + "/images/checkmark-green.png");
            break;
          }
        case triState.Invalid:
          {
            sSelector.addClass(cSS.LI.Invalid);
            img.addClass(cSS.IMG.Invalid);
            img.attr("src", prefix + "/images/not-valid-selection.png");
            break;
          }
        case triState.Empty:
        default:
          {
            img.addClass(cSS.IMG.None);
            img.attr("src", imagePath);
            break;
          }
      }
    }
    if (results.indexOf(triState.Invalid) > -1) {
      return triState.Invalid;
    }
    if (results.indexOf(triState.Empty) > -1) {
      return triState.Empty;
    }
    return triState.Valid;
  };
  const handleOnChangePassword = async event => {
    let email = null;
    let isSelf = true;
    const validationResult = handleChange(selectors.PasswordField, selectors.ConfirmPasswordField);
    if (validationResult === triState.Valid) {
      setShowError(false);
      setErrorMessage(null);
      setProcessing(true);
      let isAllowed = true;
      if (props.email !== undefined && props.email !== null) {
        email = props.email;
        isSelf = false;
      } else {
        var _state$user, _state$user2;
        const loginUserType = state === null || state === void 0 || (_state$user = state.user) === null || _state$user === void 0 || (_state$user = _state$user.userProfile) === null || _state$user === void 0 ? void 0 : _state$user.loginUserType.toString().toUpperCase();
        isAllowed = loginUserType === "BREAKGLASS" || loginUserType === "FRMUSER";
        email = state === null || state === void 0 || (_state$user2 = state.user) === null || _state$user2 === void 0 || (_state$user2 = _state$user2.userProfile) === null || _state$user2 === void 0 ? void 0 : _state$user2.email;
      }
      if (isAllowed) {
        if (props.updateLoaderStatus !== undefined) {
          props.updateLoaderStatus(true);
        }
        const payload = {
          NewPassword: (0, _jquery.default)(selectors.PasswordField).val(),
          Email: email,
          IsPasswordAutoGenerated: false
        };
        await (0, _commonService.ResetPassword)(payload).then(response => {
          if (response.length === 0) {
            addRemoveBodyOverFlowClass(false);
            setProcessing(false);
            props.callOpen(false);
            if (props.updateLoaderStatus !== undefined) {
              props.updateLoaderStatus(false);
            }
            (0, _message.default)("Password changed successfully", 2, "");
            if (isSelf === false) {
              props.navigateToGrid();
            }
          } else {
            setShowError(true);
            setProcessing(false);
            setErrorMessage("Error while changing password");
            if (props.updateLoaderStatus !== undefined) {
              props.updateLoaderStatus(false);
            }
          }
        }, err => {
          setShowError(true);
          setErrorMessage("Invalid password");
          if (props.updateLoaderStatus !== undefined) {
            props.updateLoaderStatus(false);
          }
          setProcessing(false);
        });
      } else {
        setShowError(true);
        setErrorMessage("Change password not allowed");
        setProcessing(false);
      }
    } else {
      setShowError(true);
      setErrorMessage("Please follow the password rules as mentioned above");
      setProcessing(false);
      if (props.updateLoaderStatus !== undefined) {
        props.updateLoaderStatus(false);
      }
    }
  };
  const handleClose = e => {
    props.callOpen(false);
    e.preventDefault();
  };
  const getErrorClassVariable = () => {
    const mainClassName = "error-message";
    if (showError === false) {
      return mainClassName + " hide";
    }
    return mainClassName;
  };
  const triggerChange = c => {
    const result = handleChange(selectors.PasswordField, selectors.ConfirmPasswordField);
    if (c === 0) {
      const attrName = "disabled";
      const val = (0, _jquery.default)(selectors.PasswordField).val();
      if (val && val.length > 0) {
        (0, _jquery.default)(selectors.ConfirmPasswordField).removeAttr(attrName);
      } else {
        (0, _jquery.default)(selectors.ConfirmPasswordField).attr(attrName, attrName);
      }
    } else {
      if (result === triState.Valid) {
        setShowError(false);
        setErrorMessage(null);
      }
    }
  };
  const onFormKeyInput = event => {
    if (event.which === 13) {
      handleOnChangePassword(event);
    }
  };
  const showHidePasswordFields = event => {
    setShowPassword(!showPassword);
  };
  const getMainClassName = () => {
    let cls = "modal-wrapper";
    if (props.open === true) {
      cls += " show-modal-wrapper";
    }
    cls += " reset-password";
    return cls;
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: getMainClassName(),
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "modal-block",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "confirmation-content-wrapper",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "partial-container",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: "login-block-form w-form",
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)("form", {
                id: "email-form",
                name: "email-form",
                "data-name": "Email Form",
                className: "login-form-2",
                onKeyUp: event => {
                  onFormKeyInput(event);
                },
                children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                  className: "form-block-wrapper",
                  children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                    className: "form-section-title small",
                    children: "Change password"
                  }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                      className: "field-label",
                      children: "New Password"
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
                      type: showPassword ? "text" : "password",
                      className: "input-field w-input password-field",
                      maxLength: "12",
                      name: "New-password",
                      "data-name": "New-password",
                      placeholder: "",
                      required: true,
                      onInput: () => {
                        triggerChange(0);
                      },
                      onPaste: () => {
                        triggerChange(0);
                      },
                      onChange: () => {
                        triggerChange(0);
                      },
                      onFocus: () => {
                        triggerChange(0);
                      }
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                      className: "field-label",
                      children: "Confirm New Password"
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
                      disabled: true,
                      type: showPassword ? "text" : "password",
                      className: "input-field w-input confirm-password-field",
                      maxLength: "12",
                      name: "confirm-new-password",
                      "data-name": "confirm-new-password",
                      placeholder: "",
                      id: "ConfirmPassword",
                      required: true,
                      onInput: () => {
                        triggerChange(1);
                      },
                      onPaste: () => {
                        triggerChange(1);
                      },
                      onChange: () => {
                        triggerChange(1);
                      },
                      onFocus: () => {
                        triggerChange(1);
                      }
                    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                      className: "show-password-block",
                      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
                        type: "checkbox",
                        id: "showPasswordCheckbox",
                        onClick: event => {
                          showHidePasswordFields(event);
                        }
                      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("label", {
                        children: "Show Password"
                      })]
                    })]
                  }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    className: "password-strength",
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                      className: "h6-style-guide",
                      children: "Password must include the following:"
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                      className: "form-group",
                      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("ul", {
                        className: "conditions",
                        role: "presentation",
                        "aria-atomic": "true",
                        children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
                          className: "chars",
                          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                            className: "chars-checkmark password-strength-bullet-point",
                            src: imagePath,
                            "aria-label": "criteria met"
                          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                            className: "conditions-text",
                            children: "Use between 8 and 12 characters"
                          })]
                        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
                          className: "letters",
                          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                            className: "letters-checkmark password-strength-bullet-point",
                            src: imagePath,
                            "aria-label": "criteria not met"
                          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                            className: "conditions-text",
                            children: "Include at least one lowercase (a-z) and one uppercase letter (A-Z)"
                          })]
                        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
                          className: "special",
                          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                            className: "special-checkmark password-strength-bullet-point",
                            src: imagePath,
                            "aria-label": "criteria not met"
                          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                            className: "conditions-text special-text",
                            children: "Include at least one special character e.g. $#@^\""
                          })]
                        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
                          className: "digits",
                          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                            className: "digits-checkmark password-strength-bullet-point",
                            src: imagePath,
                            "aria-label": "criteria not met"
                          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                            className: "conditions-text",
                            children: "Include at least one digit (0-9)"
                          })]
                        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
                          className: "match",
                          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                            className: "match-checkmark password-strength-bullet-point",
                            src: imagePath,
                            "aria-label": "criteria not met"
                          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                            className: "conditions-text",
                            children: "Passwords match"
                          })]
                        })]
                      })
                    })]
                  }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                    className: getErrorClassVariable(),
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                      children: errorMessage
                    })
                  })]
                })
              })
            })
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "confirmation-button-block",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            className: "confirmation-button w-button yes",
            disabled: processing,
            onClick: event => {
              handleOnChangePassword(event);
            },
            children: "Submit"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            className: "confirmation-button w-button no",
            onClick: event => {
              handleClose(event);
            },
            children: "Cancel"
          })]
        })]
      })
    })
  });
};
exports.ResetPasswordBox = ResetPasswordBox;