import _pt from "prop-types";
var _templateObject;
function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; }
/**
 * 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.
 */
import { SafeMarkdown, styled, t, getNumberFormatter, NumberFormats, computeMaxFontSize } from '@superset-ui/core';
import Handlebars from 'handlebars';
import moment from 'moment';
import React, { useMemo, useState } from 'react';
import { isPlainObject, isNumber } from 'lodash';
import Helpers from 'just-handlebars-helpers';
export var HandlebarsViewer = _ref => {
  var _common$conf$HTML_SAN, _common$conf, _common$conf2;
  var {
    templateSource,
    data
  } = _ref;
  var [renderedTemplate, setRenderedTemplate] = useState('');
  var [error, setError] = 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) || {};
  useMemo(() => {
    try {
      var template = Handlebars.compile(templateSource);
      var result = template(data);
      setRenderedTemplate(result);
      setError('');
    } catch (error) {
      setRenderedTemplate('');
      setError(error.message);
    }
  }, [templateSource, data]);
  var Error = styled.pre(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n    white-space: pre-wrap;\n  "])));
  if (error) {
    return /*#__PURE__*/React.createElement(Error, null, error);
  }
  if (renderedTemplate) {
    return /*#__PURE__*/React.createElement(SafeMarkdown, {
      source: renderedTemplate,
      htmlSanitization: htmlSanitization,
      htmlSchemaOverrides: htmlSchemaOverrides
    });
  }
  return /*#__PURE__*/React.createElement("p", null, t('Loading...'));
};

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

// usage: {{  }}
Handlebars.registerHelper('stringify', (obj, obj2) => {
  // calling without an argument
  if (obj2 === undefined) throw Error('Please call with an object. Example: `stringify myObj`');
  return isPlainObject(obj) ? JSON.stringify(obj) : String(obj);
});
Handlebars.registerHelper('numberFormat', function (value, options) {
  // Helper parameters
  var numberFormat = options.hash.numberFormat || NumberFormats.SI_3_DIGIT;
  var formatNum = 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.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 = computeMaxFontSize({
    text,
    maxWidth: width - 8,
    // Decrease 8px for more precise font size
    maxHeight: height,
    className: 'handlebar-text-line',
    container
  });
  container.remove();
  return fontSize;
});
Handlebars.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 = computeMaxFontSize({
    text,
    maxWidth: width - 8,
    // Decrease 8px for more precise font size
    maxHeight: height,
    className: 'handlebar-text-line',
    container
  });
  container.remove();
  return fontSize;
});
Handlebars.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.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.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 = isPlainObject(item) ? item : JSON.parse(item);
    ret = ret + options.fn(item);
  }
  return ret;
});
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
  if (v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
Handlebars.registerHelper('ifMore', function (v1, v2, options) {
  if (v1 > v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
Handlebars.registerHelper('ifLess', function (v1, v2, options) {
  if (v1 < v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
Handlebars.registerHelper("divide", function (a, b, options) {
  if (!isNumber(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!isNumber(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) / Number(b);
});
Handlebars.registerHelper("add", function (a, b, options) {
  if (isNumber(a) && isNumber(b)) {
    return Number(a) + Number(b);
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  }
  return '';
});
Handlebars.registerHelper("minus", function (a, b, options) {
  if (!isNumber(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!isNumber(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) - Number(b);
});
Handlebars.registerHelper("multiply", function (a, b, options) {
  if (!isNumber(a)) {
    throw new TypeError('expected the first argument to be a number');
  }
  if (!isNumber(b)) {
    throw new TypeError('expected the second argument to be a number');
  }
  return Number(a) * Number(b);
});
Helpers.registerHelpers(Handlebars);