"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EditorOutput = void 0;
var _vectorTile = require("@mapbox/vector-tile");
var _pbf = _interopRequireDefault(require("pbf"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _react = _interopRequireWildcard(require("react"));
var _mapbox_vector_tile = require("./mapbox_vector_tile");
var _output = require("../../../../models/legacy_core_editor/mode/output");
require("brace/mode/text");
require("brace/mode/hjson");
require("brace/mode/yaml");
var _shared_imports = require("../../../../../shared_imports");
var _contexts = require("../../../../contexts");
var _legacy_core_editor = require("../../../../models/legacy_core_editor");
var _subscribe_console_resize_checker = require("../subscribe_console_resize_checker");
var _apply_editor_settings = require("./apply_editor_settings");
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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

// Ensure the modes we might switch to dynamically are available

const isJSONContentType = contentType => Boolean(contentType && contentType.indexOf('application/json') >= 0);
const isMapboxVectorTile = contentType => {
  var _contentType$includes;
  return (_contentType$includes = contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/vnd.mapbox-vector-tile')) !== null && _contentType$includes !== void 0 ? _contentType$includes : false;
};

/**
 * Best effort expand literal strings
 */
const safeExpandLiteralStrings = data => {
  try {
    return (0, _shared_imports.expandLiteralStrings)(data);
  } catch (e) {
    return data;
  }
};
function modeForContentType(contentType) {
  if (!contentType) {
    return 'ace/mode/text';
  }
  if (isJSONContentType(contentType) || isMapboxVectorTile(contentType)) {
    // Using hjson will allow us to use comments in editor output and solves the problem with error markers
    return 'ace/mode/hjson';
  } else if (contentType.indexOf('application/yaml') >= 0) {
    return 'ace/mode/yaml';
  }
  return 'ace/mode/text';
}
function EditorOutputUI() {
  const editorRef = (0, _react.useRef)(null);
  const editorInstanceRef = (0, _react.useRef)(null);
  const {
    services
  } = (0, _contexts.useServicesContext)();
  const {
    settings: readOnlySettings
  } = (0, _contexts.useEditorReadContext)();
  const {
    lastResult: {
      data,
      error
    }
  } = (0, _contexts.useRequestReadContext)();
  const inputId = 'ConAppOutputTextarea';
  (0, _react.useEffect)(() => {
    editorInstanceRef.current = (0, _legacy_core_editor.createReadOnlyAceEditor)(editorRef.current);
    const unsubscribe = (0, _subscribe_console_resize_checker.subscribeResizeChecker)(editorRef.current, editorInstanceRef.current);
    const textarea = editorRef.current.querySelector('textarea');
    textarea.setAttribute('id', inputId);
    textarea.setAttribute('readonly', 'true');
    return () => {
      unsubscribe();
      editorInstanceRef.current.destroy();
    };
  }, [services.settings]);
  (0, _react.useEffect)(() => {
    const editor = editorInstanceRef.current;
    if (data) {
      const isMultipleRequest = data.length > 1;
      const mode = isMultipleRequest ? new _output.Mode() : modeForContentType(data[0].response.contentType);
      editor.update(data.map(result => {
        const {
          value,
          contentType
        } = result.response;
        let editorOutput;
        if (readOnlySettings.tripleQuotes && isJSONContentType(contentType)) {
          editorOutput = safeExpandLiteralStrings(value);
        } else if (isMapboxVectorTile(contentType)) {
          const vectorTile = new _vectorTile.VectorTile(new _pbf.default(value));
          const vectorTileJson = (0, _mapbox_vector_tile.convertMapboxVectorTileToJson)(vectorTile);
          editorOutput = safeExpandLiteralStrings(vectorTileJson);
        } else {
          editorOutput = value;
        }
        return editorOutput;
      }).join('\n'), mode);
    } else if (error) {
      const mode = modeForContentType(error.response.contentType);
      editor.update(error.response.value, mode);
    } else {
      editor.update('');
    }
  }, [readOnlySettings, data, error]);
  (0, _react.useEffect)(() => {
    (0, _apply_editor_settings.applyCurrentSettings)(editorInstanceRef.current, readOnlySettings);
  }, [readOnlySettings]);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("label", {
    htmlFor: inputId
  }, _i18n.i18n.translate('console.outputTextarea', {
    defaultMessage: 'Dev Tools Console output'
  }))), /*#__PURE__*/_react.default.createElement("div", {
    ref: editorRef,
    className: "conApp__output",
    "data-test-subj": "response-editor"
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "conApp__outputContent",
    id: "ConAppOutput"
  })));
}
const EditorOutput = /*#__PURE__*/_react.default.memo(EditorOutputUI);
exports.EditorOutput = EditorOutput;