"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FileDataVisualizerView = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _i18nReact = require("@kbn/i18n-react");
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _lodash = require("lodash");
var _about_panel = require("../about_panel");
var _results_view = require("../results_view");
var _file_error_callouts = require("./file_error_callouts");
var _edit_flyout = require("../edit_flyout");
var _explanation_flyout = require("../explanation_flyout");
var _import_view = require("../import_view");
var _utils = require("../../../common/components/utils");
var _constants = require("./constants");
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; }
/*
 * 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.
 */

class FileDataVisualizerView extends _react.Component {
  constructor(props) {
    super(props);
    (0, _defineProperty2.default)(this, "onFilePickerChange", files => {
      this.overrides = {};
      this.setState({
        loading: files.length > 0,
        loaded: false,
        fileName: '',
        fileContents: '',
        data: [],
        fileSize: 0,
        fileTooLarge: false,
        fileCouldNotBeRead: false,
        fileCouldNotBeReadPermissionError: false,
        serverError: null,
        results: undefined,
        explanation: undefined
      }, () => {
        if (files.length) {
          this.loadFile(files[0]);
        }
      });
    });
    (0, _defineProperty2.default)(this, "closeEditFlyout", () => {
      this.setState({
        isEditFlyoutVisible: false
      });
    });
    (0, _defineProperty2.default)(this, "showEditFlyout", () => {
      this.setState({
        isEditFlyoutVisible: true
      });
    });
    (0, _defineProperty2.default)(this, "closeExplanationFlyout", () => {
      this.setState({
        isExplanationFlyoutVisible: false
      });
    });
    (0, _defineProperty2.default)(this, "showExplanationFlyout", () => {
      this.setState({
        isExplanationFlyoutVisible: true
      });
    });
    (0, _defineProperty2.default)(this, "setOverrides", overrides => {
      this.setState({
        loading: true,
        loaded: false
      }, () => {
        const formattedOverrides = (0, _utils.createUrlOverrides)(overrides, this.originalSettings);
        this.analyzeFile(this.state.fileContents, formattedOverrides);
      });
    });
    (0, _defineProperty2.default)(this, "changeMode", mode => {
      this.setState({
        mode
      });
    });
    (0, _defineProperty2.default)(this, "onCancel", () => {
      this.overrides = {};
      this.previousOverrides = {};
      this.originalSettings = {
        linesToSample: _utils.DEFAULT_LINES_TO_SAMPLE
      };
      this.changeMode(_constants.MODE.READ);
      this.onFilePickerChange([]);
    });
    this.state = {
      files: {},
      fileName: '',
      fileContents: '',
      data: [],
      fileSize: 0,
      fileTooLarge: false,
      fileCouldNotBeRead: false,
      serverError: null,
      loading: false,
      loaded: false,
      results: undefined,
      explanation: undefined,
      mode: _constants.MODE.READ,
      isEditFlyoutVisible: false,
      isExplanationFlyoutVisible: false,
      hasPermissionToImport: false,
      fileCouldNotBeReadPermissionError: false
    };
    this.overrides = {};
    this.previousOverrides = {};
    this.originalSettings = {
      linesToSample: _utils.DEFAULT_LINES_TO_SAMPLE
    };
    this.maxFileUploadBytes = props.fileUpload.getMaxBytes();
  }
  async componentDidMount() {
    // check the user has the correct permission to import data.
    // note, calling hasImportPermission with no arguments just checks the
    // cluster privileges, the user will still need index privileges to create and ingest
    const hasPermissionToImport = await this.props.fileUpload.hasImportPermission({
      checkCreateDataView: false,
      checkHasManagePipeline: true
    });
    this.setState({
      hasPermissionToImport
    });
  }
  async loadFile(file) {
    if (file.size <= this.maxFileUploadBytes) {
      try {
        const {
          data,
          fileContents
        } = await (0, _utils.readFile)(file);
        this.setState({
          data,
          fileContents,
          fileName: file.name,
          fileSize: file.size
        });
        await this.analyzeFile(fileContents);
      } catch (error) {
        this.setState({
          loaded: false,
          loading: false,
          fileCouldNotBeRead: true
        });
      }
    } else {
      this.setState({
        loaded: false,
        loading: false,
        fileTooLarge: true,
        fileName: file.name,
        fileSize: file.size
      });
    }
  }
  async analyzeFile(fileContents, overrides, isRetry = false) {
    try {
      const resp = await this.props.fileUpload.analyzeFile(fileContents, overrides);
      const serverSettings = (0, _utils.processResults)(resp);
      const serverOverrides = resp.overrides;
      this.previousOverrides = overrides;
      this.overrides = {};
      if (serverSettings.format === 'xml') {
        throw {
          message: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.dataVisualizer.file.xmlNotCurrentlySupportedErrorMessage",
            defaultMessage: "XML not currently supported"
          })
        };
      }
      if (serverOverrides === undefined) {
        // if no overrides were used, store all the settings returned from the endpoint
        this.originalSettings = serverSettings;
      } else {
        Object.keys(serverOverrides).forEach(o => {
          const camelCaseO = o.replace(/_\w/g, m => m[1].toUpperCase());
          this.overrides[camelCaseO] = serverOverrides[o];
        });

        // check to see if the settings from the server which haven't been overridden have changed.
        // e.g. changing the name of the time field which is also the time field
        // will cause the timestamp_field setting to change.
        // if any have changed, update the originalSettings value
        Object.keys(serverSettings).forEach(o => {
          const value = serverSettings[o];
          if (this.overrides[o] === undefined && (Array.isArray(value) && (0, _lodash.isEqual)(value, this.originalSettings[o]) === false || value !== this.originalSettings[o])) {
            this.originalSettings[o] = value;
          }
        });
      }
      this.setState({
        results: resp.results,
        explanation: resp.explanation,
        loaded: true,
        loading: false,
        fileCouldNotBeRead: isRetry
      });
    } catch (error) {
      const fileCouldNotBeReadPermissionError = error.body.statusCode === 403;
      this.setState({
        results: undefined,
        explanation: undefined,
        loaded: false,
        loading: false,
        fileCouldNotBeRead: true,
        fileCouldNotBeReadPermissionError,
        serverError: error
      });

      // reload the results with the previous overrides
      if (isRetry === false && fileCouldNotBeReadPermissionError === false) {
        this.setState({
          loading: true,
          loaded: false
        });
        this.analyzeFile(fileContents, this.previousOverrides, true);
      }
    }
  }
  render() {
    const {
      loading,
      loaded,
      results,
      explanation,
      fileContents,
      data,
      fileName,
      fileSize,
      fileTooLarge,
      fileCouldNotBeRead,
      serverError,
      mode,
      isEditFlyoutVisible,
      isExplanationFlyoutVisible,
      hasPermissionToImport,
      fileCouldNotBeReadPermissionError
    } = this.state;
    const fields = results !== undefined && results.field_stats !== undefined ? Object.keys(results.field_stats) : [];
    return /*#__PURE__*/_react.default.createElement("div", null, mode === _constants.MODE.READ && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, !loading && !loaded && /*#__PURE__*/_react.default.createElement(_about_panel.AboutPanel, {
      onFilePickerChange: this.onFilePickerChange,
      hasPermissionToImport: hasPermissionToImport
    }), loading && /*#__PURE__*/_react.default.createElement(_about_panel.LoadingPanel, null), fileTooLarge && /*#__PURE__*/_react.default.createElement(_file_error_callouts.FileTooLarge, {
      fileSize: fileSize,
      maxFileSize: this.maxFileUploadBytes
    }), fileCouldNotBeRead && loading === false && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, fileCouldNotBeReadPermissionError ? /*#__PURE__*/_react.default.createElement(_file_error_callouts.FindFileStructurePermissionDenied, null) : /*#__PURE__*/_react.default.createElement(_file_error_callouts.FileCouldNotBeRead, {
      error: serverError,
      loaded: loaded,
      showEditFlyout: this.showEditFlyout
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "l"
    })), loaded && /*#__PURE__*/_react.default.createElement(_results_view.ResultsView, {
      results: results,
      explanation: explanation,
      fileName: fileName,
      data: fileContents,
      showEditFlyout: this.showEditFlyout,
      showExplanationFlyout: this.showExplanationFlyout,
      disableButtons: isEditFlyoutVisible || isExplanationFlyoutVisible,
      onChangeMode: this.changeMode,
      onCancel: this.onCancel,
      disableImport: hasPermissionToImport === false
    }), /*#__PURE__*/_react.default.createElement(_edit_flyout.EditFlyout, {
      setOverrides: this.setOverrides,
      closeEditFlyout: this.closeEditFlyout,
      isFlyoutVisible: isEditFlyoutVisible,
      originalSettings: this.originalSettings,
      overrides: this.overrides,
      fields: fields
    }), isExplanationFlyoutVisible && /*#__PURE__*/_react.default.createElement(_explanation_flyout.ExplanationFlyout, {
      results: results,
      closeFlyout: this.closeExplanationFlyout
    })), mode === _constants.MODE.IMPORT && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_import_view.ImportView, {
      results: results,
      fileName: fileName,
      fileContents: fileContents,
      data: data,
      dataViewsContract: this.props.dataViewsContract,
      fileUpload: this.props.fileUpload,
      getAdditionalLinks: this.props.getAdditionalLinks,
      capabilities: this.props.capabilities,
      mode: mode,
      onChangeMode: this.changeMode,
      onCancel: this.onCancel
    })));
  }
}
exports.FileDataVisualizerView = FileDataVisualizerView;