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

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

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

  ServerManager.label = function() {
    return "admin.menu.servermanager";
  };

  ServerManager.group = function() {
    return "administration";
  };

  ServerManager.submenu = function() {
    return "administration";
  };

  ServerManager.is_allowed = function() {
    if (ez5.version("6")) {
      return false;
    }
    if (ez5.session.hasSystemRight("root", "server.status")) {
      return true;
    } else {
      return false;
    }
  };

  ServerManager.path = function() {
    return ["servermanager"];
  };

  ServerManager.prototype.readOpts = function() {
    ServerManager.__super__.readOpts.call(this);
    return this.config = [];
  };

  ServerManager.prototype.load = function(ev, info) {
    ServerManager.__super__.load.call(this);
    this.pane = new CUI.BorderLayout();
    ez5.rootLayout.replace(this.pane, "center");
    new CUI.WaitBlock({
      element: this.pane.center(),
      text: $$("api.server.loading")
    }).show();
    this.getStatus();
    return CUI.resolvedPromise();
  };

  ServerManager.prototype.unload = function() {
    var ref, ref1;
    ServerManager.__super__.unload.call(this);
    if ((ref = this.pane) != null) {
      ref.destroy();
    }
    if ((ref1 = this.tabs) != null) {
      ref1.destroy();
    }
    this.pane = null;
    this.tabs = null;
    return CUI.resolvedPromise();
  };

  ServerManager.prototype.getStatus = function() {
    if (this.__purging) {
      return CUI.resolvedPromise();
    }
    return ez5.server({
      url: ez5.pluginManager.getPlugin("server").getPluginURL() + "/status",
      handle_error: (function(_this) {
        return function() {
          if (_this.__purging) {
            return true;
          }
        };
      })(this)
    }).done((function(_this) {
      return function(status) {
        _this.status = status;
        if (!_this.isLoaded()) {
          return;
        }
        return _this.show();
      };
    })(this));
  };

  ServerManager.prototype.show = function() {
    var cls, content, i, info_group, len, menu_button, post_opts, ref, ref1, tabs;
    if (!this.pane) {
      return;
    }
    if (!this.tabs) {
      tabs = [];
    }
    ref = this.status.info_groups;
    for (i = 0, len = ref.length; i < len; i++) {
      info_group = ref[i];
      cls = info_group.name;
      if (cls === "_server_time") {
        continue;
      }
      content = this.renderInfoGroup(info_group);
      if (tabs) {
        tabs.push({
          name: cls,
          text: $$("api.server.status.class." + cls),
          content: content
        });
      } else if (this.tabs.hasTab(cls)) {
        CUI.dom.replace(this.tabs.getTab(cls).getBody(), content);
      } else {
        this.tabs.destroy();
        this.tabs = null;
        return this.show();
      }
    }
    if (tabs) {
      if (ez5.session.hasSystemRight("root")) {
        post_opts = ((ref1 = ez5.session.config.defaults.server.api) != null ? ref1.settings : void 0) || {};
        menu_button = new LocaButton({
          loca_key: "server.manager.button.menu",
          menu: {
            items: (function(_this) {
              return function() {
                return [
                  {
                    loca_key: "server.manager.button.purgeall",
                    disabled: !post_opts.purgeall,
                    onClick: function() {
                      return _this.__purge("purgeall");
                    }
                  }, {
                    loca_key: "server.manager.button.purgedata",
                    disabled: !post_opts.purgedata,
                    onClick: function() {
                      return _this.__purge("purgedata");
                    }
                  }, {
                    loca_key: "server.manager.button.reindex",
                    disabled: !post_opts.reindex,
                    onClick: function() {
                      return _this.__reindex();
                    }
                  }, {
                    loca_key: "server.manager.button.restart",
                    disabled: !post_opts.restart,
                    onClick: function() {
                      return _this.__restart();
                    }
                  }, {
                    loca_key: "server.manager.button.updatecustomdata",
                    disabled: !post_opts.updatecustomdata,
                    onClick: function() {
                      return _this.__post_settings_simple("updatecustomdata", {});
                    }
                  }, {
                    loca_key: "server.manager.button.buildsuggest",
                    disabled: !post_opts.buildsuggest,
                    onClick: function() {
                      return _this.__post_settings_simple("buildsuggest", {});
                    }
                  }
                ];
              };
            })(this)
          }
        });
      }
      this.server_time = new CUI.Label();
      this.tabs = new CUI.Tabs({
        "class": "ez5-server-manager-tabs",
        tabs: tabs,
        padded: true,
        footer_left: [
          {
            loca_key: "server.manager.button.refresh",
            left: true,
            onClick: (function(_this) {
              return function(_, button) {
                button.startSpinner();
                button.disable();
                return _this.getStatus().always(function() {
                  button.stopSpinner();
                  return button.enable();
                });
              };
            })(this)
          }
        ],
        footer_right: [this.server_time, menu_button]
      });
      this.pane.replace(this.tabs, "center");
    }
    return this.server_time.setText($$("api.server.status.server_time", {
      time: this.renderDate(this.status._server_time)
    }));
  };

  ServerManager.prototype.__post_settings_simple = function(call, json_data) {
    if (json_data == null) {
      json_data = void 0;
    }
    ez5.splash.show("server.manager.spinner." + call);
    ez5.api.settings({
      type: "POST",
      json_data: json_data,
      api: "/" + call
    }).always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this)).done((function(_this) {
      return function() {
        return CUI.alert({
          markdown: true,
          text: $$("server.manager.success." + call + ".md")
        });
      };
    })(this));
  };

  ServerManager.prototype.__reindex = function() {
    return CUI.confirm({
      markdown: true,
      button_primary: "cancel",
      text: $$("server.manager.warning.confirm.reindex.md")
    }).done((function(_this) {
      return function() {
        return _this.__postSettingsAPI("reindex");
      };
    })(this));
  };

  ServerManager.prototype.__restart = function() {
    return CUI.confirm({
      markdown: true,
      button_primary: "cancel",
      text: $$("server.manager.warning.confirm.restart.md")
    }).done((function(_this) {
      return function() {
        return _this.__postSettingsAPI("restart");
      };
    })(this));
  };

  ServerManager.prototype.__purge = function(call) {
    return CUI.confirm({
      markdown: true,
      button_primary: "cancel",
      text: $$("server.manager.warning." + call + ".md")
    }).done((function(_this) {
      return function() {
        var inst;
        inst = ez5.session.getInstance().name;
        return CUI.prompt({
          markdown: true,
          "class": "no-user-select",
          text: $$("server.manager.warning.confirm.md", {
            instance: inst
          }),
          button_primary: "cancel",
          min_length: inst.length
        }).done(function(value) {
          if (inst !== value) {
            return;
          }
          return _this.__postSettingsAPI(call);
        });
      };
    })(this));
  };

  ServerManager.prototype.__postSettingsAPI = function(call) {
    var wait;
    ez5.eventPoller.stop();
    this.__purging = true;
    wait = false;
    return ez5.api.settings({
      type: "POST",
      api: "/" + call,
      handle_error: (function(_this) {
        return function(xhr) {
          if (xhr.status === 500 || xhr.status === 502) {
            wait = true;
            return true;
          }
        };
      })(this)
    }).always((function(_this) {
      return function() {
        var interval;
        if (!wait) {
          return;
        }
        ez5.splash.show("server.manager.splash.waiting");
        return interval = window.setInterval(function() {
          return ez5.api.settings({
            timeout: 500,
            handle_error: function(xhr) {
              return true;
            }
          }).fail(function(xhr) {
            if (xhr.status === 500 || xhr.status === 502) {
              return true;
            }
            if (xhr.CUI_statusText === "timeout") {
              return true;
            }
            window.clearInterval(interval);
            ez5.splash.hide();
            return CUI.problem({
              text: $$("server.manager.warning.reset_failed")
            });
          }).done(function() {
            window.clearInterval(interval);
            ez5.splash.hide();
            if (call === "restart" || call === "reindex") {
              return CUI.alert({
                markdown: true,
                text: $$("server.manager.warning." + call + ".md"),
                button_text_ok: $$("server.manager.button.reload")
              }).done(function() {
                return document.location.reload();
              });
            } else {
              return CUI.alert({
                markdown: true,
                text: $$("server.manager.warning.reload.md"),
                button_text_ok: $$("server.manager.button.reload")
              }).done(function() {
                return document.location.assign("/");
              });
            }
          });
        }, 2500);
      };
    })(this));
  };

  ServerManager.prototype.renderInfoGroup = function(info_group) {
    var blk, block, content, i, len, list, ref;
    list = [];
    ref = info_group.info;
    for (i = 0, len = ref.length; i < len; i++) {
      block = ref[i];
      switch (block.type) {
        case "map":
          content = this.renderMap(info_group.name, block);
          break;
        case "2d-map":
          content = this.render2DMapVertical(info_group.name, block);
          break;
        default:
          console.error("ServerManager.renderClass", "block.type \"" + block.type + "\" unknown. Skipping. Block:", block);
      }
      blk = new CUI.Block({
        text: $$("api.server.status.block." + info_group.name + "." + block.name),
        padded: false,
        content: content
      });
      list.push(blk);
    }
    return new CUI.VerticalList({
      content: list
    });
  };

  ServerManager.prototype.renderMap = function(cls, block) {
    var format, i, len, ref, ref1, tbl, v, value;
    tbl = CUI.dom.table("status-map");
    ref = block.data;
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      ref1 = this.renderValue(value), v = ref1[0], format = ref1[1];
      CUI.dom.append(tbl, CUI.dom.tr_one_row($$("api.server.status.value." + cls + "." + block.name + "." + value.name), v));
    }
    return tbl;
  };

  ServerManager.prototype.render2DMapHorizontal = function(cls, block) {
    var _cls, arr, children, classes, col, i, idx, j, k, l, len, len1, len2, len3, ref, ref1, ref2, ref3, tbl, tr, v, value;
    tbl = CUI.dom.table("status-2d-map status-2d-map-horizontal");
    arr = [$$("api.server.status.headers." + cls + "." + block.name + "." + block.headers.name)];
    ref = block.headers.values;
    for (i = 0, len = ref.length; i < len; i++) {
      col = ref[i];
      arr.push(col);
    }
    CUI.dom.append(tbl, CUI.dom.tr_one_row.apply(this, arr));
    ref1 = block.data;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      value = ref1[j];
      arr = [$$("api.server.status.value." + cls + "." + block.name + "." + value.name)];
      classes = [""];
      ref2 = value.values;
      for (idx = k = 0, len2 = ref2.length; k < len2; idx = ++k) {
        v = ref2[idx];
        ref3 = this.renderValue(value, idx), v = ref3[0], _cls = ref3[1];
        arr.push(v);
        classes.push(_cls);
      }
      tr = CUI.dom.tr_one_row.apply(this, arr);
      children = tr.children;
      for (idx = l = 0, len3 = classes.length; l < len3; idx = ++l) {
        _cls = classes[idx];
        CUI.dom.addClass(children[idx], _cls);
      }
      CUI.dom.append(tbl, tr);
    }
    return tbl;
  };

  ServerManager.prototype.render2DMapVertical = function(cls, block) {
    var col, columns, i, idx, j, k, len, len1, len2, ref, ref1, ref2, row, rows, text, v, value;
    text = $$("api.server.status.headers." + cls + "." + block.name + "." + block.headers.name);
    columns = [
      {
        text: text ? text : " ",
        name: "column-" + block.name
      }
    ];
    ref = block.data;
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      text = $$("api.server.status.value." + cls + "." + block.name + "." + value.name);
      columns.push({
        text: text ? text : " ",
        name: "column-" + value.name
      });
    }
    rows = [];
    ref1 = block.headers.values;
    for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
      col = ref1[idx];
      row = [block.headers.values[idx]];
      ref2 = block.data;
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        value = ref2[k];
        v = this.renderValue(value, idx)[0];
        row.push(v);
      }
      rows.push(row);
    }
    return new CUI.Table({
      bordered: true,
      "class": "status-2d-map status-2d-map-horizontal",
      header: true,
      columns: columns,
      rows: rows
    });
  };

  ServerManager.prototype.renderValue = function(value, idx) {
    var cls, v;
    if (parseInt(idx) >= 0) {
      v = value.values[idx];
    } else {
      v = value.value;
    }
    switch (value.type) {
      case "date":
        v = this.renderDate(v);
        cls = "right";
        break;
      case "json":
        v = this.renderJSON(v);
        cls = "right";
        break;
      case "error":
        v = this.renderError(value);
        cls = "right";
    }
    if (value.unit) {
      switch (value.unit) {
        case "bytes":
          v = ez5.format_filesize(v);
          cls = "right";
          break;
        case "completion":
          v = v.toFixed(2) + "%";
          cls = "right";
          break;
        case "s":
          v = ez5.format_seconds(v);
          cls = "right";
          break;
        default:
          v += " " + value.unit;
      }
    }
    return [v, cls];
  };

  ServerManager.prototype.renderDate = function(str) {
    return ez5.format_date_and_time(str, true);
  };

  ServerManager.prototype.renderJSON = function(data) {
    if (!CUI.util.isArray(data) && !CUI.util.isPlainObject(data)) {
      return;
    }
    if (CUI.util.isEmpty(data)) {
      return;
    }
    if (CUI.util.isArray(data) && data.every((function(_this) {
      return function(_data) {
        return !CUI.util.isArray(_data) && !CUI.util.isPlainObject(_data);
      };
    })(this))) {
      return data.join(", ");
    }
    return new CUI.ObjectDumper({
      object: data
    });
  };

  ServerManager.prototype.renderError = function(value) {
    return new CUI.Label({
      "class": "ez5-server-manager-error-value",
      text: $$(value.error.code, value.error.parameters),
      markdown: true,
      multiline: true
    }).DOM;
  };

  return ServerManager;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(ServerManager);
});
