"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFileExtension = getFileExtension;
exports.validateFile = validateFile;
var _i18n = require("@kbn/i18n");
var _get_max_bytes = require("./get_max_bytes");
/*
 * 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.
 */

/*
 * Extract file extension from file. Example: file.name "points.geojson" returns ".geojson"
 */
function getFileExtension(file) {
  const extension = file.name.split('.').pop();
  return '.' + extension;
}
function validateFile(file, types, options) {
  if (file.size > (0, _get_max_bytes.getMaxBytes)() && options !== null && options !== void 0 && options.checkSizeLimit) {
    throw new Error(_i18n.i18n.translate('xpack.fileUpload.fileSizeError', {
      defaultMessage: 'File size {fileSize} exceeds maximum file size of {maxFileSize}',
      values: {
        fileSize: bytesToSize(file.size),
        maxFileSize: (0, _get_max_bytes.getMaxBytesFormatted)()
      }
    }));
  }
  if (!file.name) {
    throw new Error(_i18n.i18n.translate('xpack.fileUpload.noFileNameError', {
      defaultMessage: 'File name not provided'
    }));
  }
  if (!types.includes(getFileExtension(file))) {
    throw new Error(_i18n.i18n.translate('xpack.fileUpload.fileTypeError', {
      defaultMessage: 'File is not one of acceptable types: {types}',
      values: {
        types: types.join(', ')
      }
    }));
  }
}
function bytesToSize(bytes) {
  if (bytes === 0) return 'n/a';
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.round(Math.floor(Math.log(bytes) / Math.log(1024)));
  if (i === 0) return `${bytes} ${sizes[i]})`;
  return `${(bytes / 1024 ** i).toFixed(1)} ${sizes[i]}`;
}