"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.validateNotInUse = exports.isValidPassword = exports.isValidEmail = exports.hasBlockingError = void 0;
var _recordDataHelpers = require("./recordDataHelpers");
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation
// eslint-disable-next-line max-len
const emailPattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const isValidEmail = email => emailPattern.test(email);
exports.isValidEmail = isValidEmail;
const isValidPassword = password => password && password.length >= 8 && password.length <= 24;
exports.isValidPassword = isValidPassword;
const isBlocking = validationError => {
  const nonblocking = validationError.get('nonblocking');
  return typeof nonblocking === 'undefined' ? true : !nonblocking;
};
const hasBlockingError = validationErrors => {
  if (!validationErrors) {
    return false;
  }
  const error = validationErrors.get(_recordDataHelpers.ERROR_KEY);
  if (error && isBlocking(error)) {
    return true;
  }
  return validationErrors.entrySeq().filter(_ref => {
    let [key] = _ref;
    return key !== _recordDataHelpers.ERROR_KEY;
  })
  // eslint-disable-next-line no-unused-vars
  .find(_ref2 => {
    let [key, child] = _ref2;
    return hasBlockingError(child);
  });
};
exports.hasBlockingError = hasBlockingError;
const validateNotInUse = _ref3 => {
  let {
    configContext,
    validationContext,
    fieldName
  } = _ref3;
  const {
    actions,
    config,
    configHelpers,
    lib
  } = configContext;
  const {
    csid,
    data: value,
    recordType
  } = validationContext;
  const {
    findFirst
  } = actions;
  if (!value) {
    return undefined;
  }
  return findFirst(config, recordType, fieldName, value).then(response => {
    const {
      lodash
    } = lib;
    const existingCsid = lodash.get(response, ['data', 'ns2:abstract-common-list', 'list-item', 'csid']);
    if (existingCsid && existingCsid !== csid) {
      const {
        fieldDescriptor
      } = validationContext;
      return {
        value,
        code: 'ID_IN_USE',
        message: lodash.get(fieldDescriptor, [configHelpers.configKey, 'messages', 'inUse']),
        nonblocking: true
      };
    }
    return undefined;
  });
};
exports.validateNotInUse = validateNotInUse;