"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = createHtmlImageAtom;

var _handlebars = _interopRequireDefault(require("handlebars"));

var _path = _interopRequireDefault(require("path"));

var _utils = require("../../../utils");

var _templates = require("../templates");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Create HTML content for ImageAtom
 * @param {object} atom atom json
 * @param {string} outputPath path to save the assets folder for images
 * @returns {string} HTML content
 */
async function createHtmlImageAtom(atom, outputPath) {
  let {
    caption
  } = atom;
  const {
    url
  } = atom; // create directory for image assets

  const pathImg = (0, _utils.makeDir)(outputPath, 'img'); // if link doesn't contain image extension, create a custom file name

  let filename;

  if (!_path.default.extname(url)) {
    filename = `${atom.id}.gif`;
  } // download image first and save it


  const promiseDownload = (0, _utils.downloadImage)(url, pathImg, filename);
  const promiseLoadTemplate = (0, _templates.loadTemplate)('atom.image');
  const [filenameImg, html] = await Promise.all([promiseDownload, promiseLoadTemplate]);
  const alt = caption;
  caption = (0, _utils.markdownToHtml)(caption);
  const dataTemplate = {
    file: `img/${filenameImg}`,
    alt,
    caption
  };

  const template = _handlebars.default.compile(html);

  return template(dataTemplate);
}