"use strict";

exports.__esModule = true;
exports.HandlebarsViewer = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _core = require("@superset-ui/core");
var _handlebars = _interopRequireDefault(require("handlebars"));
var _moment = _interopRequireDefault(require("moment"));
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _justHandlebarsHelpers = _interopRequireDefault(require("just-handlebars-helpers"));
var _templateObject;
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; }
var HandlebarsViewer = _ref => {
  var _common$conf$HTML_SAN, _common$conf, _common$conf2;
  var {
    templateSource,
    data
  } = _ref;
  var [renderedTemplate, setRenderedTemplate] = (0, _react.useState)('');
  var [error, setError] = (0, _react.useState)('');
  var appContainer = document.getElementById('app');
  var {
    common
  } = JSON.parse((appContainer == null ? void 0 : appContainer.getAttribute('data-bootstrap')) || '{}');
  var htmlSanitization = (_common$conf$HTML_SAN = common == null || (_common$conf = common.conf) == null ? void 0 : _common$conf.HTML_SANITIZATION) != null ? _common$conf$HTML_SAN : true;
  var htmlSchemaOverrides = (common == null || (_common$conf2 = common.conf) == null ? void 0 : _common$conf2.HTML_SANITIZATION_SCHEMA_EXTENSIONS) || {};
  (0, _react.useMemo)(() => {
    try {
      var template = _handlebars.default.compile(templateSource);
      var result = template(data);
      setRenderedTemplate(result);
      setError('');
    } catch (error) {
      setRenderedTemplate('');
      setError(error.message);
    }
  }, [templateSource, data]);
  var Error = _core.styled.pre(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n    white-space: pre-wrap;\n  "])));
  if (error) {
    return /*#__PURE__*/_react.default.createElement(Error, null, error);
  }
  if (renderedTemplate) {
    return /*#__PURE__*/_react.default.createElement(_core.SafeMarkdown, {
      source: renderedTemplate,
      htmlSanitization: htmlSanitization,
      htmlSchemaOverrides: htmlSchemaOverrides
    });
  }
  return /*#__PURE__*/_react.default.createElement("p", null, (0, _core.t)('Loading...'));
};

//  usage: {{dateFormat my_date format="MMMM YYYY"}}
exports.HandlebarsViewer = HandlebarsViewer;
HandlebarsViewer.propTypes = {
  templateSource: _propTypes.default.string.isRequired,
  data: _propTypes.default.any.isRequired
};
_handlebars.default.registerHelper('dateFormat', function (context, block) {
  var f = block.hash.format || 'YYYY-MM-DD';
  return (0, _moment.default)(context).format(f);
});

// usage: {{  }}
_handlebars.default.registerHelper('stringify', (obj, obj2) => {
  // calling without an argument
  if (obj2 === undefined) throw Error('Please call with an object. Example: `stringify myObj`');
  return (0, _lodash.isPlainObject)(obj) ? JSON.stringify(obj) : String(obj);
});
_handlebars.default.registerHelper('numberFormat', function (value, options) {
  // Helper parameters
  var numberFormat = options.hash.numberFormat || _core.NumberFormats.SI_3_DIGIT;
  var formatNum = (0, _core.getNumberFormatter)(numberFormat);
  return formatNum(value);
});
function createTemporaryContainer() {
  var container = document.createElement('div');
  container.className = 'className';
  container.style.position = 'absolute'; // so it won't disrupt page layout
  container.style.opacity = '0'; // and not visible
  return container;
}
_handlebars.default.registerHelper('computeMaxFontSize', function (text, className, idealFontSize, options) {
  // Helper parameters

  var elements = document.getElementsByClassName(className);
  if ((elements == null ? void 0 : elements.length) === 0) {
    return idealFontSize;
  }
  var element = elements[0];
  var computedStyle = getComputedStyle(element);
  var height = element.clientHeight - parseFloat(computedStyle.paddingTop) - parseFloat(computedStyle.paddingBottom);
  var width = element.clientWidth - parseFloat(computedStyle.paddingLeft) - parseFloat(computedStyle.paddingRight);
  var container = createTemporaryContainer();
  document.body.append(container);
  var fontSize = (0, _core.computeMaxFontSize)({
    text,
    maxWidth: width - 8,
    // Decrease 8px for more precise font size
    maxHeight: height,
    className: 'handlebar-text-line',
    container
  });
  container.remove();
  return fontSize;
});
_handlebars.default.registerHelper('computeMaxFontSizeHeight', function (text, className, height, idealFontSize, options) {
  // Helper parameters

  var elements = document.getElementsByClassName(className);
  if ((elements == null ? void 0 : elements.length) === 0) {
    return idealFontSize;
  }
  var element = elements[0];
  var computedStyle = getComputedStyle(element);
  var width = element.clientWidth - parseFloat(computedStyle.paddingLeft) - parseFloat(computedStyle.paddingRight);
  var container = createTemporaryContainer();
  document.body.append(container);
  var fontSize = (0, _core.computeMaxFontSize)({
    text,
    maxWidth: width - 8,
    // Decrease 8px for more precise font size
    maxHeight: height,
    className: 'handlebar-text-line',
    container
  });
  container.remove();
  return fontSize;
});
_handlebars.default.registerHelper('getElemWidth', function (className, defaultWidth, options) {
  // Helper parameters

  var elements = document.getElementsByClassName(className);
  if ((elements == null ? void 0 : elements.length) === 0) {
    return defaultWidth;
  }
  var element = elements[0];
  var computedStyle = getComputedStyle(element);
  return element.clientWidth - parseFloat(computedStyle.paddingLeft) - parseFloat(computedStyle.paddingRight);
});
_handlebars.default.registerHelper('jsonParse', (obj, obj2) => {
  // calling without an argument
  if (obj2 === undefined) throw Error('Please call with an object. Example: `stringify myObj`');
  return JSON.parse(obj);
});
_handlebars.default.registerHelper("jsonEach", function (context, max, options) {
  var ret = "";
  context = JSON.parse(context);
  for (var i = 0; i < max && i < ((_context = context) == null ? void 0 : _context.length); i++) {
    var _context;
    var item = context[i];
    item = (0, _lodash.isPlainObject)(item) ? item : JSON.parse(item);
    ret = ret + options.fn(item);
  }
  return ret;
});
_handlebars.default.registerHelper('ifCond', function (v1, v2, options) {
  if (v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
_handlebars.default.registerHelper('ifMore', function (v1, v2, options) {
  if (v1 > v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
_handlebars.default.registerHelper('ifLess', function (v1, v2, options) {
  if (v1 < v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
_handlebars.default.registerHelper("divide", function (a, b, options) {
  if (!(0, _lodash.isNumber)(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!(0, _lodash.isNumber)(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) / Number(b);
});
_handlebars.default.registerHelper("add", function (a, b, options) {
  if ((0, _lodash.isNumber)(a) && (0, _lodash.isNumber)(b)) {
    return Number(a) + Number(b);
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  }
  return '';
});
_handlebars.default.registerHelper("minus", function (a, b, options) {
  if (!(0, _lodash.isNumber)(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!(0, _lodash.isNumber)(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) - Number(b);
});
_handlebars.default.registerHelper("multiply", function (a, b, options) {
  if (!(0, _lodash.isNumber)(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!(0, _lodash.isNumber)(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) * Number(b);
});
_justHandlebarsHelpers.default.registerHelpers(_handlebars.default);