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

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

  Header.prototype.initOpts = function() {
    Header.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        check: "PlainObject",
        "default": {}
      }
    });
  };

  Header.prototype.readOpts = function() {
    var i, len, position, ref;
    Header.__super__.readOpts.call(this);
    this.__data = this._data;
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      if (this.__data[position]) {
        continue;
      }
      this.__data[position] = {};
    }
    return this;
  };

  Header.prototype.getData = function() {
    return this.__data;
  };

  Header.prototype.renderPdfContent = function(opts) {
    var _data, asset, assetImg, centerDiv, children, data, dfr, div, easID, fn, header, i, img, imgDiv, imgEl, j, k, len, len1, len2, loadPromises, node, object, position, ref, ref1, ref2, ref3, ref4, text, textNodes, width;
    if (!opts.header_loaded && !opts.preview) {
      loadPromises = [];
      ref = ["left", "center", "right"];
      fn = (function(_this) {
        return function(position) {
          var easID, imagePromise, ref1, ref2;
          if (_this.__data[position].type === "image" && ((ref1 = _this.__data[position]["file:eas_file"]) != null ? ref1._id : void 0)) {
            if (_this.__imagesData == null) {
              _this.__imagesData = {};
            }
            easID = (ref2 = _this.__data[position]["file:eas_file"]) != null ? ref2._id : void 0;
            if (_this.__imagesData[easID]) {
              return;
            }
            imagePromise = new CUI.Deferred();
            ez5.api.eas({
              type: "GET",
              data: {
                ids: JSON.stringify([easID]),
                format: "long"
              }
            }).done(function(easData) {
              var imageRequest, ref3, ref4, ref5;
              imageRequest = new CUI.XHR({
                method: "GET",
                url: Session.addToken((ref3 = easData[easID]) != null ? (ref4 = ref3.versions) != null ? (ref5 = ref4.original) != null ? ref5.url : void 0 : void 0 : void 0),
                responseType: "blob"
              });
              return imageRequest.start().done(function(blob) {
                var fileReader;
                fileReader = new FileReader();
                fileReader.readAsDataURL(blob);
                return fileReader.onloadend = function() {
                  _this.__imagesData[easID] = fileReader.result;
                  return imagePromise.resolve();
                };
              });
            });
            return loadPromises.push(imagePromise.promise());
          }
        };
      })(this);
      for (i = 0, len = ref.length; i < len; i++) {
        position = ref[i];
        fn(position);
      }
      if (loadPromises.length > 0) {
        dfr = new CUI.Deferred();
        CUI.whenAll(loadPromises).done((function(_this) {
          return function() {
            opts.header_loaded = true;
            return dfr.resolve(_this.renderPdfContent(opts));
          };
        })(this));
        return dfr.promise();
      }
    }
    header = CUI.dom.div("pdf-node-" + (this.constructor.name.toLowerCase()));
    if (!opts.preview) {
      CUI.dom.setStyle(header, {
        "font-size": "8px",
        "padding-left": "0.28in",
        "padding-right": "0.28in",
        "width": "calc(100% - 0.56in)"
      });
    }
    data = this.getData();
    ref1 = ["left", "center", "right"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      position = ref1[j];
      div = CUI.dom.div();
      CUI.dom.append(header, div);
      CUI.dom.setStyle(div, {
        "display": "inline-block",
        "text-align": position,
        "min-height": opts.preview ? "12px" : "8px"
      });
      _data = data[position];
      switch (_data.type) {
        case "logo":
          if (!ez5.PdfCreator.logoImage) {
            continue;
          }
          CUI.dom.setStyle(div, {
            "min-height": 0
          });
          img = CUI.dom.element("img", {
            src: ez5.PdfCreator.logoImage
          });
          imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
          CUI.dom.append(imgDiv, img);
          if (!opts.preview) {
            CUI.dom.setStyle(img, {
              "height": "0.3in"
            });
          }
          CUI.dom.append(div, imgDiv);
          break;
        case "image":
          if (!opts.preview) {
            CUI.dom.setStyle(div, {
              "min-height": 0
            });
            easID = (ref2 = _data["file:eas_file"]) != null ? ref2._id : void 0;
            img = CUI.dom.element("img", {
              src: this.__imagesData[easID]
            });
            imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
            CUI.dom.append(imgDiv, img);
            CUI.dom.setStyle(img, {
              "height": "0.3in"
            });
          } else {
            if (!((ref3 = _data["file:eas_file"]) != null ? ref3._id : void 0)) {
              continue;
            }
            asset = new AssetPlain({
              value: _data["file:eas_file"]
            });
            imgDiv = CUI.dom.div("pdf-node-header-image-" + position);
            assetImg = asset.getImgElement(null, "original", {
              for_print: true
            });
            imgEl = assetImg.querySelector("img");
            if (imgEl) {
              CUI.dom.append(imgDiv, imgEl);
            } else {
              CUI.dom.append(imgDiv, assetImg);
            }
          }
          CUI.dom.append(div, imgDiv);
          break;
        default:
          text = ez5.loca.getBestFrontendValue(_data.text);
          if (!text) {
            continue;
          }
          CUI.dom.setStyle(div, {
            "white-space": "nowrap",
            "overflow": "hidden"
          });
          text = text.replace(/%pageNumber%/g, "<span class='pageNumber'>1</span>");
          text = text.replace(/%totalPages%/g, "<span class='totalPages'>" + (((ref4 = opts.objects) != null ? ref4.length : void 0) || 1) + "</span>");
          object = opts.objects[0];
          text = ez5.PdfCreatorUtils.replaceTextPlaceholders(text, object);
          textNodes = CUI.dom.htmlToNodes(text);
          CUI.dom.append(div, textNodes);
      }
    }
    centerDiv = header.children[1];
    if (!centerDiv.hasChildNodes()) {
      centerDiv.remove();
    }
    children = CUI.dom.children(header);
    width = 100 / children.length;
    for (k = 0, len2 = children.length; k < len2; k++) {
      node = children[k];
      CUI.dom.setStyle(node, {
        "width": width + "%"
      });
    }
    return header;
  };

  Header.prototype.getSettingsFields = function(opts) {
    var forms, getFields, i, len, position, ref;
    if (opts == null) {
      opts = {};
    }
    getFields = (function(_this) {
      return function(position) {
        var customImageField, eas_field, formFields, logoFieldDisabled, logoText, onDataChanged, textField, textHintButton;
        textHintButton = new CUI.Button({
          text: $$("pdf-creator.settings.node.header.text|hint"),
          appearance: "flat",
          onClick: function() {
            var pop;
            pop = new ez5.HintPopover({
              element: textHintButton,
              content: new CUI.Label({
                text: $$("pdf-creator.settings.node.header.text.popover"),
                markdown: true
              }),
              padded: true
            });
            return pop.show();
          }
        });
        textField = {
          type: CUI.MultiInput,
          form: {
            label: $$("pdf-creator.settings.node.header.text|label"),
            hint: textHintButton
          },
          control: ez5.loca.getLanguageControl(),
          name: "text"
        };
        eas_field = new EASField({
          name: "file:eas_file"
        });
        customImageField = {
          type: CUI.DataFieldProxy,
          form: {
            label: $$("pdf-creator.settings.node.eas.file")
          },
          name: "file:eas_file",
          element: function(df) {
            return eas_field.renderEditorInput(df.getData(), null);
          }
        };
        if (position === "center" || !_this.__supportsLogo()) {
          return [textField];
        }
        onDataChanged = function(data, field) {
          var form;
          form = field.getForm();
          textField = form.getFieldsByName("text")[0];
          customImageField = form.getFieldsByName("file:eas_file")[0];
          switch (data.type) {
            case "logo":
              textField.hide(true);
              customImageField.hide(true);
              break;
            case "text":
              textField.show(true);
              customImageField.hide(true);
              break;
            default:
              textField.hide(true);
              customImageField.show(true);
          }
        };
        logoFieldDisabled = !ez5.PdfCreator.logoImage;
        if (logoFieldDisabled) {
          logoText = $$("pdf-creator.settings.node.header.select.option-logo-disabled|label");
        } else {
          logoText = $$("pdf-creator.settings.node.header.select.option-logo|label");
        }
        formFields = [
          {
            type: CUI.Select,
            name: "type",
            form: {
              label: $$("pdf-creator.settings.node.header.select|label")
            },
            options: [
              {
                text: $$("pdf-creator.settings.node.header.select.option-text|label"),
                value: "text"
              }, {
                text: logoText,
                value: "logo",
                disabled: logoFieldDisabled
              }, {
                text: $$("pdf-creator.settings.node.header.select.option-image|label"),
                value: "image"
              }
            ],
            onDataInit: function(field, data) {
              return onDataChanged(data, field);
            },
            onDataChanged: onDataChanged
          }, textField, customImageField
        ];
        return formFields;
      };
    })(this);
    forms = [];
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      forms.push({
        type: CUI.Form,
        form: {
          label: $$("pdf-creator.settings.node.header.title." + position + "|label")
        },
        render_as_block: true,
        name: position,
        fields: getFields(position),
        data: this.getData()
      });
    }
    return forms;
  };

  Header.prototype.__supportsLogo = function() {
    return true;
  };

  Header.prototype.getSaveData = function() {
    var data, i, len, position, ref;
    data = this.getData();
    ref = ["left", "center", "right"];
    for (i = 0, len = ref.length; i < len; i++) {
      position = ref[i];
      if (CUI.util.isEmpty(data[position]["file:eas_file"])) {
        delete data[position]["file:eas_file"];
      }
    }
    return CUI.util.copyObject(this.getData(), true);
  };

  return Header;

})(CUI.Element);
