// 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.PdfCreator = (function(superClass) {
  extend(PdfCreator, superClass);

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

  PdfCreator.VERSION = 2;

  PdfCreator.prototype.initOpts = function() {
    PdfCreator.__super__.initOpts.call(this);
    this.addOpts({
      data: {
        check: "PlainObject",
        "default": {}
      },
      idObjecttype: {
        check: "Integer",
        mandatory: true
      },
      idMask: {
        check: "Integer"
      }
    });
    return this;
  };

  PdfCreator.prototype.readOpts = function() {
    var i, len, name, pdfCreatorPlugin, plugin, plugins, promiseCssPlugin, promiseCssPrint, ref, ref1, ref2, ref3, url;
    PdfCreator.__super__.readOpts.call(this);
    if (!ez5.PdfCreator.nodePlugins) {
      plugins = {};
      ref = ez5.PdfCreator.plugins.getPlugins();
      for (i = 0, len = ref.length; i < len; i++) {
        plugin = ref[i];
        name = plugin.getName();
        if (plugins[name]) {
          console.warn("PdfCreator :: Skipping plugin with duplicated name: " + name);
          continue;
        }
        plugins[name] = plugin;
      }
      ez5.PdfCreator.nodePlugins = plugins;
    }
    if (!ez5.PdfCreator.fetchPrintCSSPromise) {
      ez5.PdfCreator.printSyles = "";
      pdfCreatorPlugin = ez5.pluginManager.getPlugin("pdf-creator");
      promiseCssPlugin = new CUI.XHR({
        url: ez5.getAbsoluteURL(pdfCreatorPlugin.getBaseURL() + pdfCreatorPlugin.getWebfrontend().print_css),
        responseType: "text"
      }).start().done((function(_this) {
        return function(styles) {
          return ez5.PdfCreator.printSyles += styles;
        };
      })(this));
      promiseCssPrint = new CUI.XHR({
        url: Start.getCSSUrl("print", ez5.session.getCSSMode()),
        responseType: "text"
      }).start().done((function(_this) {
        return function(styles) {
          return ez5.PdfCreator.printSyles += styles;
        };
      })(this));
      ez5.PdfCreator.fetchPrintCSSPromise = CUI.whenAll(promiseCssPlugin, promiseCssPrint);
    }
    url = (ref1 = ez5.session.getConfigPicture("logo")) != null ? (ref2 = ref1.versions) != null ? (ref3 = ref2.original) != null ? ref3.url : void 0 : void 0 : void 0;
    if (url && !ez5.PdfCreator.logoImage) {
      promiseCssPlugin = new CUI.XHR({
        method: "GET",
        url: url,
        responseType: "blob"
      });
      promiseCssPlugin.start().done((function(_this) {
        return function(blob) {
          var fileReader;
          fileReader = new FileReader();
          fileReader.readAsDataURL(blob);
          return fileReader.onloadend = function() {
            ez5.PdfCreator.logoImage = fileReader.result;
            return promiseCssPlugin.destroy();
          };
        };
      })(this));
    }
    if (!this._data.templates) {
      this._data.templates = [];
    }
    return this;
  };

  PdfCreator.prototype.renderList = function() {
    var _, cols, copyButton, data, downloadTemplatesButton, editButton, header, i, j, len, len1, minusButton, pane, plusButton, ref, ref1, uploadTemplatesButton;
    header = ez5.PdfCreator.Template.Row.getHeader();
    cols = [];
    ref = header.getColumns();
    for (i = 0, len = ref.length; i < len; i++) {
      _ = ref[i];
      cols.push("auto");
    }
    this.__listView = new CUI.ListView({
      rowMove: false,
      cols: cols,
      selectableRows: true,
      fixedRows: 1,
      onSelect: (function(_this) {
        return function() {
          minusButton.enable();
          editButton.enable();
          return copyButton.enable();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          minusButton.disable();
          editButton.disable();
          return copyButton.disable();
        };
      })(this)
    });
    this.__listView.appendRow(header);
    plusButton = new CUI.Button({
      icon: "plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          return _this.__showModal();
        };
      })(this)
    });
    minusButton = new CUI.Button({
      icon: "minus",
      group: "plus-minus",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          CUI.confirm({
            text: $$("pdf-creator.list.confirmation.remove-template|text")
          }).done(function() {
            var data, selectedRow;
            selectedRow = _this.__getSelectedRow();
            data = selectedRow.getData();
            selectedRow.remove();
            CUI.util.removeFromArray(data, _this._data.templates);
            CUI.Events.trigger({
              type: "data-changed",
              node: _this.__listView
            });
            minusButton.disable();
            editButton.disable();
            return copyButton.disable();
          });
        };
      })(this)
    });
    editButton = new CUI.Button({
      icon: "edit",
      group: "edit-copy",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var data;
          data = _this.__getSelectedRow().getData();
          _this.__showModal(data);
        };
      })(this)
    });
    copyButton = new CUI.Button({
      icon: "fa-files-o",
      group: "edit-copy",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var copiedData;
          copiedData = CUI.util.copyObject(_this.__getSelectedRow().getData(), true);
          _this.__addRow(copiedData);
          _this._data.templates.push(copiedData);
          CUI.Events.trigger({
            type: "data-changed",
            node: _this.__listView
          });
        };
      })(this)
    });
    downloadTemplatesButton = new LocaButton({
      loca_key: "pdf-creator.list.download-templates.button",
      group: "download-upload",
      onClick: (function(_this) {
        return function() {
          var data;
          data = {
            version: ez5.PdfCreator.VERSION,
            templates: _this._data.templates
          };
          return CUI.FileReader.save(ez5.session.getEasydbName() + "-pdf-templates.json", JSON.stringify(data, null, "    "));
        };
      })(this)
    });
    uploadTemplatesButton = new CUI.FileUploadButton({
      fileUpload: new CUI.FileReader({
        onDone: (function(_this) {
          return function(fileReaderResult) {
            var data, j, len1, ref1, template;
            try {
              data = JSON.parse(fileReaderResult.getResult());
              if (data.version !== ez5.PdfCreator.VERSION) {
                CUI.problem({
                  text: $$("pdf-creator.list.upload-templates.wrong-version-error", {
                    file_version: data.version,
                    version: ez5.PdfCreator.VERSION
                  })
                });
                return;
              }
              if (CUI.util.isEmpty(data.templates)) {
                CUI.problem({
                  text: $$("pdf-creator.list.upload-templates.no-templates-error")
                });
                return;
              }
              ref1 = data.templates;
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                template = ref1[j];
                _this.__addRow(template);
                _this._data.templates.push(template);
              }
              CUI.Events.trigger({
                type: "data-changed",
                node: _this.__listView
              });
            } catch (error) {
              CUI.problem({
                text: $$("pdf-creator.list.upload-templates.json-error")
              });
            }
          };
        })(this)
      }),
      tooltip: {
        text: $$("pdf-creator.list.upload-templates.button|tooltip")
      },
      icon: $$("pdf-creator.list.upload-templates.button|icon"),
      group: "download-upload",
      multiple: false
    });
    pane = new CUI.SimplePane({
      footer_left: new CUI.Buttonbar({
        buttons: [plusButton, minusButton, editButton, copyButton, downloadTemplatesButton, uploadTemplatesButton]
      }),
      content: this.__listView
    });
    ref1 = this._data.templates;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      data = ref1[j];
      this.__addRow(data);
    }
    this.__listView.render();
    return pane;
  };

  PdfCreator.prototype.__addRow = function(data) {
    var row, template;
    template = new ez5.PdfCreator.Template({
      data: data
    });
    row = new ez5.PdfCreator.Template.Row({
      template: template
    });
    this.__listView.appendRow(row);
  };

  PdfCreator.prototype.__getSelectedRow = function() {
    return this.__listView.getSelectedRows()[0];
  };

  PdfCreator.prototype.__showModal = function(data) {
    var pdfCreatorModal;
    pdfCreatorModal = new ez5.PdfCreator.Modal({
      idObjecttype: this._idObjecttype,
      idMask: this._idMask,
      data: data,
      onSave: (function(_this) {
        return function(dataSaved) {
          var ref;
          if (!_this._data.templates.includes(dataSaved)) {
            _this._data.templates.push(dataSaved);
            _this.__addRow(dataSaved);
          }
          CUI.Events.trigger({
            type: "data-changed",
            node: _this.__listView
          });
          if ((ref = _this.__getSelectedRow()) != null) {
            ref.reload();
          }
        };
      })(this)
    });
    pdfCreatorModal.open();
  };

  PdfCreator.prototype.getTemplateSelect = function(selectOpts) {
    var data, defaultOpts, displayName, i, len, options, ref, template;
    if (selectOpts == null) {
      selectOpts = {};
    }
    options = [
      {
        text: $$("pdf-creator.select.option.not-selected|text"),
        value: null
      }
    ];
    ref = this._data.templates;
    for (i = 0, len = ref.length; i < len; i++) {
      data = ref[i];
      template = new ez5.PdfCreator.Template({
        data: data
      });
      displayName = template.getDisplayName();
      options.push({
        text: displayName,
        value: data
      });
    }
    selectOpts.options = options;
    defaultOpts = {
      name: "pdf_creator_template"
    };
    CUI.util.mergeMap(selectOpts, defaultOpts);
    return new CUI.Select(selectOpts);
  };

  PdfCreator.print = function(data, objects, idMask) {
    var pdfCreatorTemplate;
    pdfCreatorTemplate = new ez5.PdfCreator.Template({
      data: data
    });
    return pdfCreatorTemplate.print(objects, idMask);
  };

  PdfCreator.getPlugin = function(name) {
    return this.nodePlugins[name];
  };

  PdfCreator.getTemplateFields = function(pdfTemplateData) {
    var collectFields, pdfTemplateFields, topNodes;
    pdfTemplateFields = {};
    topNodes = pdfTemplateData.documentData.children;
    collectFields = function(pdfNodes) {
      var fieldName, fieldValue, i, len, node, selectedFields;
      for (i = 0, len = pdfNodes.length; i < len; i++) {
        node = pdfNodes[i];
        if (node.data.dataFields) {
          selectedFields = ez5.PdfCreator.Node.Field.getSelectedFields(node.data);
          for (fieldName in selectedFields) {
            fieldValue = selectedFields[fieldName];
            pdfTemplateFields[fieldName] = fieldValue;
            pdfTemplateFields[fieldName].display_name = ez5.loca.getBestFrontendValue(fieldValue.label);
          }
        }
        if (node.children) {
          collectFields(node.children);
        }
      }
    };
    collectFields(topNodes);
    return pdfTemplateFields;
  };

  return PdfCreator;

})(CUI.Element);
