// Generated by CoffeeScript 1.12.7
var FalconIODownloadManager,
  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;

FalconIODownloadManager = (function(superClass) {
  extend(FalconIODownloadManager, superClass);

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

  FalconIODownloadManager.prototype.type = function() {
    return "falconio";
  };

  FalconIODownloadManager.prototype.getType = function() {
    return "falconio";
  };

  FalconIODownloadManager.prototype.acceptVersionForDownload = function(version) {
    return true;
  };

  FalconIODownloadManager.prototype.sendData = function(form_data, filepicker_files) {
    var baseConfig, base_conf, deferred, preflighturl, url, xhr2;
    deferred = new CUI.Deferred;
    baseConfig = ez5.session.getBaseConfig("plugin", "easydb-falconio-plugin");
    baseConfig = baseConfig.system || baseConfig;
    base_conf = baseConfig[this.type()] || {};
    preflighturl = "https://cors-anywhere.herokuapp.com/";
    url = "";
    xhr2 = new CUI.XHR({
      method: "POST",
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      url: preflighturl + base_conf.falconio_url + this._collection.auth,
      body: JSON.stringify(form_data)
    });
    xhr2.start().done((function(_this) {
      return function(data) {
        var event;
        event = filepicker_files.event;
        event.info[_this.__type] = data;
        event.type = _this.__TYPE + '_FILE_COPY';
        EventPoller.saveEvent(event);
        return deferred.resolve();
      };
    })(this)).fail((function(_this) {
      return function() {
        var _xhr, event, fault, text;
        _xhr = xhr2.getXHR();
        event = filepicker_files.event;
        event.type = _this.__TYPE + '_FILE_COPY_ERROR';
        if (_xhr.responseJSON) {
          event.info.error = _xhr.responseJSON;
        } else {
          event.info.error = xhr2.statusText() + ":" + (_xhr.response || "<Empty Response>");
        }
        fault = _xhr.response.fault.faultstring;
        _this.__upload_errors = _this.__upload_errors + 1;
        if (fault.includes("ApiKey")) {
          text = "" + fault + ". API Key '" + _this._collection.auth + "' is unreachable. Request is " + _xhr.statusText;
        } else {
          text = fault;
        }
        _this.__upload_error = {
          title: fault,
          text: text
        };
        EventPoller.saveEvent(event);
        return deferred.reject();
      };
    })(this));
    return deferred.promise();
  };

  FalconIODownloadManager.prototype.sendFiles = function(filepicker_files, blobs) {
    var dfr, get_form_data, go_on, overwrite, overwrite_files, send_data, show_report;
    dfr = new CUI.Deferred();
    send_data = true;
    overwrite_files = [];
    overwrite = null;
    this.__upload_errors = null;
    get_form_data = (function(_this) {
      return function(files, blobs) {
        var form_data;
        files = files[0];
        if (blobs[files.path]["type"].indexOf("image") !== -1) {
          form_data = {
            'content': {
              'picture': {
                message: "Sent on " + new Date().toLocaleDateString(),
                url: files.url,
                originalPicture: files.url,
                fileName: files.title + files.filename.substring(files.filename.indexOf("."))
              }
            },
            'tags': ["easydb"]
          };
          return form_data;
        } else if (blobs[files.path]["type"].indexOf("stream") !== -1) {
          form_data = {
            'content': {
              'video': {
                message: "Sent on " + new Date().toLocaleDateString(),
                url: files.url,
                fileName: files.title + files.filename.substring(files.filename.indexOf("."))
              }
            },
            'tags': ["easydb"]
          };
          return form_data;
        }
      };
    })(this);
    show_report = (function(_this) {
      return function() {
        var attrs, loca, ref, type;
        attrs = {
          errors: _this.__upload_errors,
          count: filepicker_files.length,
          success: filepicker_files.length - _this.__upload_errors
        };
        if (attrs.errors > 0) {
          loca = 'error';
          type = 'problem';
        } else {
          loca = 'success';
          type = 'alert';
        }
        CUI[type]({
          text: _this.__upload_error.text
        });
        return (ref = window.opener) != null ? ref.postMessage({
          easydb: {
            action: 'reload'
          }
        }, '*') : void 0;
      };
    })(this);
    dfr.always((function(_this) {
      return function() {
        return _this.hideProgress();
      };
    })(this));
    dfr.done((function(_this) {
      return function() {};
    })(this));
    dfr.fail((function(_this) {
      return function() {
        if (_this.__upload_errors === null) {
          return;
        }
        return show_report();
      };
    })(this));
    go_on = (function(_this) {
      return function() {
        _this.__upload_errors = 0;
        return CUI.chunkWork.call(_this, {
          items: filepicker_files,
          chunk_size: 1,
          timeout: 0,
          call: function(items, idx, len) {
            var file, form_data;
            _this.showProgress(_this.__type + '.download.manager.sending_files', {
              number: idx + 1,
              count: len
            });
            file = items[0];
            form_data = get_form_data([file], blobs);
            console.debug("appending file", blobs[file.path], file);
            return _this.sendData(form_data, file);
          }
        }).done(dfr.resolve).fail(dfr.reject);
      };
    })(this);
    if (overwrite_files.length > 0) {
      new CUI.ConfirmationChoice({
        text: $$(this.__type + '.download.manager.ask_overwrite_files.msg.md', {
          count: overwrite_files.length
        }),
        choices: [
          {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.cancel',
            cancel: true
          }, overwrite_files.length < filepicker_files.length ? {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.skip',
            choice: 'skip'
          } : void 0, {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.overwrite',
            choice: 'overwrite',
            primary: true
          }
        ]
      }).open().done((function(_this) {
        return function(choice) {
          var i, len1, overwrite_file;
          switch (choice.choice) {
            case 'skip':
              for (i = 0, len1 = overwrite_files.length; i < len1; i++) {
                overwrite_file = overwrite_files[i];
                removeFromArray(overwrite_file, filepicker_files);
              }
              break;
            case 'overwrite':
          }
          return go_on();
        };
      })(this)).fail(dfr.reject);
    } else {
      go_on();
    }
    return dfr.promise();
  };

  FalconIODownloadManager.prototype.startExport = function() {
    var dfr;
    dfr = new CUI.Deferred();
    this.init().fail(dfr.reject).done((function(_this) {
      return function() {
        return _this.gatherBaseData().fail(dfr.reject).done(function() {
          return _this.showUserAdminMessages().fail(dfr.reject).done(function() {
            var alert, content, mod, show_error, text, title;
            mod = null;
            _this.saveButton = new LocaButton({
              loca_key: _this.getButtonStartLocaKey(),
              left: true,
              onClick: function(ev) {
                mod.disableAllButtons();
                _this.saveButton.setIcon("spinner");
                return _this.saveExport(ev).done(function() {
                  dfr.resolve();
                  return mod.destroy();
                }).fail(function() {
                  _this.saveButton.setIcon();
                  return mod.enableAllButtons();
                });
              }
            });
            content = _this.getContent();
            alert = null;
            if (content.length === 3) {
              alert = content[2];
              content.splice(2, 1);
            }
            show_error = function() {
              return CUI.problem({
                text: _this.getDownloadPrepareError()
              }).done(dfr.reject);
            };
            if (!content[0] && !alert) {
              show_error();
              return;
            }
            if (content[0]) {
              CUI.chainedCall(content).done(function(_content) {
                mod = new CUI.ConfirmationDialog({
                  icon: $$("download.manager.modal.icon"),
                  title: _this.getTitle(),
                  "class": "ez5-download-manager-confirmation-dialog ez5-event-poller",
                  cancel: true,
                  onCancel: function() {
                    dfr.reject("user_rejected");
                  },
                  content: _content,
                  buttons: function() {
                    return [_this.saveButton];
                  }
                }).show();
                return dfr.notify("modal_open");
              }).fail(function() {
                return show_error();
              });
            }
            if (alert) {
              if (alert === "too_many_files") {
                text = $$("falconio.too_many_files.text");
                title = $$("falconio.too_many_files.title");
              } else {
                title = $$("falconio.unsupported_filetype.title");
                text = $$("falconio.unsupported_filetype.text") + " " + alert;
              }
              new CUI.Alert({
                title: title,
                text: text
              }).open();
              if (!content[0]) {
                dfr.reject("user_rejected");
              }
            }
          });
        });
      };
    })(this));
    return dfr.promise();
  };

  FalconIODownloadManager.prototype.getContent = function() {
    var add_metadata, alert, bottom, cls, eas_info, i, label, label_txt, len1, loca_key, mf, opts, ref, ref1, size, stat, stat_warning, stats, version_stat, vn, vprint;
    this.form_fields = [];
    label_txt = [];
    eas_info = this.getEASColumnsInfo();
    stats = eas_info.counts;
    stat_warning = false;
    alert = null;
    if (eas_info.total > 150) {
      return [null, null, "too_many_files"];
    }
    ref = stats.by_class;
    for (cls in ref) {
      stat = ref[cls];
      if (cls === "3d" || cls === "audio" || cls === "archive") {
        if (alert !== null) {
          alert += ", " + cls;
        } else {
          alert = cls;
        }
        continue;
      }
      if (!stat.total) {
        continue;
      }
      if (cls === "image" || cls === "audio" || cls === "video") {
        add_metadata = true;
      }
      label_txt.push(stat.total + "x " + $$("server.eas.fileclass." + cls));
      opts = [];
      ref1 = Asset.getExportVersionNamesForClass(cls, true);
      for (i = 0, len1 = ref1.length; i < len1; i++) {
        vn = ref1[i];
        if (stat.versions) {
          version_stat = stat.versions[vn];
          if (!(version_stat != null ? version_stat.total : void 0)) {
            continue;
          }
        } else {
          stat_warning = true;
          if (vn === "original") {
            version_stat = stat;
          } else {
            version_stat = null;
          }
        }
        if (!this.form_data[cls]) {
          this.form_data[cls] = vn;
        }
        if (version_stat) {
          size = ez5.format_filesize(version_stat.acc_filesize);
          loca_key = "download.manager.version.with_size";
        } else {
          loca_key = "download.manager.version.without_size";
        }
        if (vn === "original") {
          vprint = $$("download.manager.format.original");
        } else {
          vprint = Asset.getPrintSizeForVersion(cls, vn);
        }
        opts.push({
          text: $$(loca_key, {
            size: size,
            version: vprint,
            count: version_stat != null ? version_stat.total : void 0
          }),
          value: vn
        });
      }
      if (cls === "office") {
        opts.splice(0, 1);
        label_txt.push($$("falconio.no_office_support.text"));
      }
      this.form_fields.push({
        form: {
          label: $$("server.eas.fileclass." + cls)
        },
        name: cls,
        type: CUI.Options,
        radio: true,
        min_checked: 0,
        options: opts,
        undo_support: false
      });
    }
    if (this.form_fields.length === 0) {
      return [null, null, alert];
    }
    mf = this.getMetadataField();
    if (add_metadata && mf) {
      this.form_fields.push(mf);
    } else {
      this.form_data._metadata = "standard";
    }
    this.form_fields.push(this.getFilenameTemplateField());
    label = new CUI.Label({
      "class": "ez5-download-manager-status",
      text: "Status",
      multiline: true
    });
    label.setText(label_txt.join(", "));
    bottom = CUI.dom.space();
    bottom.appendChild(label.DOM);
    if (stat_warning) {
      bottom.appendChild(new CUI.EmptyLabel({
        text: $$("download.manager.no_stats_hint")
      }).DOM);
    }
    return [
      new CUI.Form({
        fields: this.form_fields,
        onDataChanged: (function(_this) {
          return function() {
            var ref2, v;
            ref2 = _this.form_data;
            for (cls in ref2) {
              v = ref2[cls];
              if (cls.startsWith("_")) {
                continue;
              }
              if (v !== false) {
                _this.saveButton.enable();
                return;
              }
            }
            return _this.saveButton.disable();
          };
        })(this),
        data: this.form_data
      }).start(), bottom, alert
    ];
  };

  return FalconIODownloadManager;

})(FilepickerDownloadManager);
// Generated by CoffeeScript 1.12.7
var FalconIOFilepicker,
  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;

FalconIOFilepicker = (function(superClass) {
  extend(FalconIOFilepicker, superClass);

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

  FalconIOFilepicker.prototype.type = function() {
    return 'falconio';
  };

  FalconIOFilepicker.prototype.readOpts = function() {
    FalconIOFilepicker.__super__.readOpts.call(this);
    return this.setDownloadManagerClass(FalconIODownloadManager);
  };

  FalconIOFilepicker.prototype.getCurrentTools = function(col) {
    var baseConfig, base_conf, bool, count, i, inst, j, len, len1, ref, ref1, that, tool, tools;
    baseConfig = ez5.session.getBaseConfig("plugin", "easydb-falconio-plugin");
    baseConfig = baseConfig.system || baseConfig;
    base_conf = baseConfig[this.type()] || {};
    bool = false;
    ref = base_conf.fio_instances || [];
    for (i = 0, len = ref.length; i < len; i++) {
      inst = ref[i];
      if (inst.active && inst.auth !== "") {
        bool = true;
      }
    }
    if (!ez5.session.hasSystemRight("root", "plugin.easydb-falconio-plugin.falconio")) {
      return;
    }
    if (!bool) {
      return;
    }
    if (!(col instanceof CollectionSelection)) {
      return tools;
    }
    count = col.getCount();
    if (count === 0) {
      return tools;
    }
    base_conf.send_files = true;
    base_conf.falconio_url = "https://api.falcon.io/publish/publishing/template?apikey=";
    tools = [];
    tool = [];
    count = col.getCount();
    that = this;
    ref1 = base_conf.fio_instances;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      inst = ref1[j];
      if (inst.active && inst.auth !== "") {
        tool.push(new ToolboxTool({
          group: col.getToolGroup(),
          name: col.getToolNamePrefix() + '.' + this.__type + '.download.' + inst.name,
          text: inst.name,
          run: function() {
            var k, len2, ref2, x;
            ref2 = base_conf.fio_instances;
            for (k = 0, len2 = ref2.length; k < len2; k++) {
              x = ref2[k];
              if (x.name === this.opts.text) {
                col.auth = x.auth;
              }
            }
            new that.__downloadManagerCls({
              collection: col
            }).startExport();
          }
        }));
      }
    }
    tools.push(new ToolboxTool({
      group: col.getToolGroup(),
      name: col.getToolNamePrefix() + '.' + this.__type + '.download',
      sort: "D:3",
      loca_key: "tool." + col.getToolNamePrefix() + '.' + this.__type + '.download',
      tools: tool,
      loca_key_attrs: {
        count: count
      },
      favorite: true
    }));
    return tools;
  };

  return FalconIOFilepicker;

})(Filepicker);

ez5.session_ready(function() {
  return Collection.registerPlugin(new FalconIOFilepicker());
});
