"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkIndexPatternValid = checkIndexPatternValid;
exports.validateIndexName = void 0;
var _i18n = require("@kbn/i18n");
var _kibana_services = require("./kibana_services");
var _api = require("./api");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function checkIndexPatternValid(name) {
  const byteLength = encodeURI(name).split(/%(?:u[0-9A-F]{2})?[0-9A-F]{2}|./).length - 1;
  const reg = new RegExp('[\\\\/*?"<>|\\s,#]+');
  const indexPatternInvalid = byteLength > 255 ||
  // name can't be greater than 255 bytes
  name !== name.toLowerCase() ||
  // name should be lowercase
  name === '.' || name === '..' ||
  // name can't be . or ..
  name.match(/^[-_+]/) !== null ||
  // name can't start with these chars
  name.match(reg) !== null; // name can't contain these chars
  return !indexPatternInvalid;
}
const validateIndexName = async indexName => {
  if (!indexName) {
    return _i18n.i18n.translate('xpack.fileUpload.indexNameRequired', {
      defaultMessage: 'Index name required'
    });
  }
  if (!checkIndexPatternValid(indexName)) {
    return _i18n.i18n.translate('xpack.fileUpload.indexNameContainsIllegalCharactersErrorMessage', {
      defaultMessage: 'Index name contains illegal characters.'
    });
  }
  const dataViewNames = await (0, _kibana_services.getDataViewsService)().getTitles();
  if (dataViewNames.includes(indexName)) {
    return _i18n.i18n.translate('xpack.fileUpload.dataViewAlreadyExistsErrorMessage', {
      defaultMessage: 'Data view already exists.'
    });
  }
  const indexExists = await (0, _api.checkIndexExists)(indexName);
  if (indexExists) {
    return _i18n.i18n.translate('xpack.fileUpload.indexNameAlreadyExistsErrorMessage', {
      defaultMessage: 'Index name already exists.'
    });
  }
};
exports.validateIndexName = validateIndexName;