"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

require("core-js/modules/web.dom-collections.iterator.js");

require("core-js/modules/es.promise.js");

require("core-js/modules/es.json.stringify.js");

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactRouterDom = require("react-router-dom");

var _formik = require("formik");

var Yup = _interopRequireWildcard(require("yup"));

var _antd = require("antd");

var _localforage = _interopRequireDefault(require("localforage"));

var _freeRegularSvgIcons = require("@fortawesome/free-regular-svg-icons");

var _reactFontawesome = require("@fortawesome/react-fontawesome");

var _constant = require("../constant");

require("antd/dist/antd.css");

var _SigninFormModule = _interopRequireDefault(require("./SigninForm.module.scss"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

const SigninForm = _ref => {
  let {
    background,
    textColor,
    label,
    storeToken,
    authhandlerUrl,
    backendUrl
  } = _ref;
  const [isAuthenticate, setAuthenticationStatus] = (0, _react.useState)(undefined);
  const [loading, setLoading] = (0, _react.useState)(false);
  const INITIAL_DATA_API = "".concat(backendUrl, "/staff/initial-data");
  const SIGNIN_API = "".concat(authhandlerUrl, "/auth");

  const initialDataHeaders = _objectSpread(_objectSpread({}, _constant.signinApiHeaders), {}, {
    organizationname: "hcinbox"
  });

  const navigate = (0, _reactRouterDom.useNavigate)();
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit
  } = (0, _formik.useFormik)({
    initialValues: {
      email: "",
      password: ""
    },
    validationSchema: Yup.object().shape({
      email: Yup.string().email("Invalid email address format").required("Email required"),
      password: Yup.string().matches(/^(?=.*[A-Za-z])(?=.*[@$!%*#?&])[A-Za-z0-9@$!%*#?&]{6,}$/, "Password should be atleast 6 characters long and should contain a special symbol!").required("Password required")
    }),
    onSubmit: async values => {
      submitSignInForm(values);
    }
  });

  const submitSignInForm = async _ref2 => {
    let {
      email,
      password
    } = _ref2;

    try {
      setLoading(true);
      const token = await fetch(SIGNIN_API, {
        method: "POST",
        headers: _constant.signinApiHeaders,
        body: JSON.stringify({
          username: email,
          password
        })
      });
      const tokenSet = await token.json();
      storeToken(tokenSet);
      initialDataHeaders.Authorization = "Bearer ".concat(tokenSet.access_token);
      let userDetails = await fetch(INITIAL_DATA_API, {
        headers: initialDataHeaders
      });

      if (!userDetails.ok) {
        throw new Error(userDetails);
      }

      userDetails = await userDetails.json();

      if (!userDetails.success) {
        throw new Error("Server Error!");
      }

      localStorage.setItem("userDetails", JSON.stringify(userDetails.data));
      setAuthenticationStatus(true);
      setLoading(false);
      navigate("/chat");
    } catch (error) {
      setLoading(false);
      setAuthenticationStatus(false);
      console.log(error);
    }
  };

  const handleValidationStatus = key => {
    return !touched[key] && !errors[key] ? "" : touched[key] && !errors[key] ? "success" : touched[key] && errors[key] ? "error" : "";
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm,
    "data-testid": "sign-in-form"
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__signInContainer
  }, /*#__PURE__*/_react.default.createElement("h3", null, "Great to have you here!"), /*#__PURE__*/_react.default.createElement("form", {
    onSubmit: handleSubmit
  }, /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem,
    label: "Enter email address",
    name: "email",
    validateStatus: handleValidationStatus("email"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input, {
    id: "email",
    name: "email",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.email,
    placeholder: "example@gmail.com"
  }), touched.email && errors.email ? /*#__PURE__*/_react.default.createElement("div", {
    role: "alert",
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem__error
  }, errors.email) : null), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem,
    label: "Enter the Password",
    name: "password",
    validateStatus: handleValidationStatus("password"),
    hasFeedback: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Input.Password, {
    id: "password",
    name: "password",
    type: "text",
    onChange: handleChange,
    onBlur: handleBlur,
    value: values.password,
    placeholder: "Password"
  }), touched.password && errors.password ? /*#__PURE__*/_react.default.createElement("div", {
    role: "alert",
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem__error
  }, errors.password) : null), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    className: _SigninFormModule.default.SigninForm__signInContainer__formItem
  }, /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "remember",
    valuePropName: "checked",
    noStyle: true
  }, /*#__PURE__*/_react.default.createElement(_antd.Checkbox, null, "Remember me")), /*#__PURE__*/_react.default.createElement("a", {
    href: ""
  }, "Forgot password")), /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__signInContainer__btnContainer
  }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
    style: {
      background: background,
      color: textColor
    },
    loading: loading,
    htmlType: "submit"
  }, label, /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_reactFontawesome.FontAwesomeIcon, {
    icon: _freeRegularSvgIcons.faArrowAltCircleRight
  })))), /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__signInContainer__helpMsg
  }, "Not yet registered? ", /*#__PURE__*/_react.default.createElement("a", {
    onClick: () => navigate("/signup")
  }, "Create an account")), isAuthenticate === false ? /*#__PURE__*/_react.default.createElement("div", {
    className: _SigninFormModule.default.SigninForm__alert
  }, /*#__PURE__*/_react.default.createElement(_antd.Alert, {
    message: "Error",
    description: "Couldn\u2019t find a HCInbox account associated with this credentials. Please try again.",
    type: "error",
    showIcon: true
  })) : null)));
};

SigninForm.propTypes = {
  background: _propTypes.default.string,
  textColor: _propTypes.default.string,
  label: _propTypes.default.string,
  size: _propTypes.default.string
};
SigninForm.defaultProps = {
  background: "rgba(9, 109, 217, 1)",
  textColor: "white",
  label: "Login",
  size: "medium"
};
var _default = SigninForm;
exports.default = _default;