'use strict';

var utils = require('./utils.js');

const TemplateCache = function() {
  var cache = {};
  return {
    load: (url, serviceUrl, client) => {
      var p = cache[url];
      if (!p) {
        cache[url] = p = client.get(url).then((html) => {
          var templates = {};
          var styleSheets = [];
          var baseUri = utils.rTrim(serviceUrl, "\\/") + "/";
          html = utils.replaceAll(html, "{service}/", baseUri);
          html = utils.replaceAll(html, "{service}", baseUri);
          var viewerTemplate = $("<div></div>").html(html);
          Array.from(viewerTemplate.find("template")).forEach((element) => {
            var $element = $(element);
            templates[$element.attr("id")] = utils.trim($element.html(), "\n 	");
          });
          Array.from(viewerTemplate.find("link")).forEach((element) => {
            styleSheets.push(utils.trim(element.outerHTML, "\n 	"));
          });
          styleSheets = utils.filterUniqueLastOccurrence(styleSheets);
          return {
            templates,
            styleSheets
          };
        });
      }
      return p;
    }
  };
}();

exports.TemplateCache = TemplateCache;
