// Generated by CoffeeScript 1.12.7
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ez5.PdfCreatorUtils = (function(superClass) {
  extend(PdfCreatorUtils, superClass);

  function PdfCreatorUtils() {
    return PdfCreatorUtils.__super__.constructor.apply(this, arguments);
  }

  PdfCreatorUtils.print = function(objects, pdfDocumentNode) {
    var deferred, fylrUrl, html2pdfUrl, ref, spinner;
    if (objects == null) {
      objects = [];
    }
    spinner = CUI.spinner({
      text: $$("pdf-creator.print.preparing.text")
    });
    if (!pdfDocumentNode || !(pdfDocumentNode instanceof ez5.PdfCreator.Node.Document)) {
      return CUI.rejectedPromise("PdfCreatorUtils.print :: pdfDocument needs to be defined and it needs to be an instance of ez5.PdfCreator.Node.Document", pdfDocumentNode);
    }
    fylrUrl = (ref = ez5.session.getBaseConfig("plugin", "pdf-creator").pdf_creator) != null ? ref.fylr_url : void 0;
    if (CUI.util.isEmpty(fylrUrl)) {
      if (!ez5.version("6")) {
        spinner.destroy();
        return CUI.rejectedPromise($$("pdf-creator.print-url-not-configured"));
      } else if (ez5.pluginManager.getPlugin("server-pdf")) {
        html2pdfUrl = CUI.parseLocation(ez5.pluginManager.getPlugin("server-pdf").getPluginURL()).path;
        fylrUrl = Session.addToken(html2pdfUrl + "/html2pdf");
      } else {
        spinner.destroy();
        return CUI.rejectedPromise($$("pdf-creator.print-url-not-configured.fylr"));
      }
    }
    deferred = new CUI.Deferred();
    this.fetchLinkedObjects(objects).done((function(_this) {
      return function() {
        var customCssUrl, header, headerPromise, html, opts, ref1;
        opts = {
          objects: objects,
          styles: ez5.PdfCreator.printSyles,
          spinner: spinner
        };
        customCssUrl = (ref1 = ez5.session.getBaseConfig("plugin", "pdf-creator").pdf_creator) != null ? ref1.custom_css_url : void 0;
        if (customCssUrl) {
          opts.custom_css_url = customCssUrl;
        }
        html = pdfDocumentNode.renderPdf(opts).outerHTML;
        html = html.replace(/loading="lazy"/g, "");
        headerPromise = pdfDocumentNode.renderHeader(opts);
        header = null;
        if (CUI.util.isPromise(headerPromise)) {
          headerPromise.done(function(headerDOM) {
            return header = headerDOM.outerHTML.replace(/loading="lazy"/g, "");
          });
        } else {
          header = headerPromise.outerHTML.replace(/loading="lazy"/g, "");
          headerPromise = CUI.resolvedPromise();
        }
        return headerPromise.done(function() {
          var data, filename, footer, margins, xhr;
          footer = pdfDocumentNode.renderFooter(opts).outerHTML;
          footer = footer.replace(/loading="lazy"/g, "");
          margins = pdfDocumentNode.getMargins();
          filename = pdfDocumentNode.getFilename(objects[0]);
          data = {
            file_name: filename,
            document: html,
            properties: {
              displayHeaderFooter: true,
              printBackground: true,
              headerTemplate: header,
              footerTemplate: footer,
              landscape: pdfDocumentNode.isLandscape(),
              paperWidth: pdfDocumentNode.getPaperWidth(),
              paperHeight: pdfDocumentNode.getPaperHeight(),
              marginTop: margins.top,
              marginBottom: margins.bottom,
              marginLeft: margins.left,
              marginRight: margins.right
            }
          };
          spinner.updateText($$("pdf-creator.print.rendering.text"));
          spinner.autoSize();
          xhr = new CUI.XHR({
            method: "POST",
            url: fylrUrl,
            body: JSON.stringify(data),
            responseType: "blob"
          });
          return xhr.start().done(function(response) {
            CUI.FileReader.save(filename, response, "application/pdf");
            return deferred.resolve();
          }).fail(deferred.reject).always(function() {
            return spinner.destroy();
          });
        });
      };
    })(this));
    return deferred.promise();
  };

  PdfCreatorUtils.initDocumentData = function(data) {
    var children, initNodes;
    initNodes = (function(_this) {
      return function(children) {
        var child, i, len, node, nodes, plugin;
        nodes = [];
        if (!children) {
          return null;
        }
        for (i = 0, len = children.length; i < len; i++) {
          child = children[i];
          plugin = ez5.PdfCreator.getPlugin(child.name);
          if (!plugin) {
            console.warn("PdfCreator :: Load :: Skipping unknown type of plugin, name: '" + child.name + "'");
            continue;
          }
          node = new plugin({
            data: child.data,
            open: child.open,
            children: initNodes(child.children)
          });
          nodes.push(node);
        }
        return nodes;
      };
    })(this);
    children = data.children;
    if (children) {
      data.children = initNodes(children);
    }
    return data;
  };

  PdfCreatorUtils.fetchLinkedObjects = function(objects) {
    var deferred, findLinkedObject, i, len, object, objectsToFetch;
    objectsToFetch = {};
    findLinkedObject = function(object) {
      var _, _value, format, formatIncomplete, globalObjectId, i, len, value;
      if (!CUI.util.isPlainObject(object)) {
        return;
      }
      globalObjectId = object._global_object_id;
      format = object._format;
      formatIncomplete = object._format_incomplete;
      if (globalObjectId && (format !== "long" || formatIncomplete)) {
        if (!objectsToFetch[globalObjectId]) {
          objectsToFetch[globalObjectId] = [];
        }
        objectsToFetch[globalObjectId].push(object);
      }
      for (_ in object) {
        value = object[_];
        if (CUI.util.isArray(value)) {
          for (i = 0, len = value.length; i < len; i++) {
            _value = value[i];
            findLinkedObject(_value);
          }
        } else {
          findLinkedObject(value);
        }
      }
    };
    for (i = 0, len = objects.length; i < len; i++) {
      object = objects[i];
      findLinkedObject(object);
    }
    if (CUI.util.isEmptyObject(objectsToFetch)) {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    ez5.api.search_no_limit({
      json_data: {
        limit: 1000000,
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_global_object_id"],
            "in": Object.keys(objectsToFetch)
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var _objectLongFormat, _objects, j, k, len1, len2, ref;
        ref = data.objects;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          _objectLongFormat = ref[j];
          _objects = objectsToFetch[_objectLongFormat._global_object_id] || [];
          for (k = 0, len2 = _objects.length; k < len2; k++) {
            object = _objects[k];
            CUI.util.mergeMap(object, _objectLongFormat);
            object._format = _objectLongFormat._format;
          }
        }
        return deferred.resolve();
      };
    })(this));
    return deferred.promise();
  };

  PdfCreatorUtils.replaceTextPlaceholders = function(text, object) {
    var i, key, len, ref, ref1, regexp, standardText;
    text = text.replace(/%username%/g, ez5.session.getUser().getDisplayText());
    text = text.replace(/%date%/g, ez5.format_date(CUI.util.moment()));
    if (!object) {
      return text;
    }
    ref = ["_global_object_id", "_system_object_id"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      regexp = new RegExp("%" + key + "%", "g");
      text = text.replace(regexp, object[key] || key);
    }
    standardText = ez5.loca.getBestFrontendValue((ref1 = object._standard["1"]) != null ? ref1.text : void 0) || "-";
    text = text.replace(/%_standard\.1\.text%/g, standardText);
    return text;
  };

  return PdfCreatorUtils;

})(CUI.Element);
