// Generated by CoffeeScript 1.12.7

/*
 * easydb-editor-tagfilter-defaults
 * Copyright (c) 2013 - 2016 Programmfabrik GmbH
 * MIT Licence
 * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
 */
var BaseConfigEditorTagfilterDefaults, EditorTagfilterDefaults,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  EditorTagfilterDefaults.prototype.readOpts = function() {
    var baseConfig, filter, filters, filters_by_mask_name, i, len, listenTypes, mask_name, ref, ref1;
    EditorTagfilterDefaults.__super__.readOpts.call(this);
    BaseConfig.registerPlugin(new BaseConfigEditorTagfilterDefaults());
    filters_by_mask_name = {};
    baseConfig = ez5.session.getBaseConfig("plugin", "easydb-editor-tagfilter-defaults-plugin");
    baseConfig = baseConfig.system || baseConfig;
    filters = ((ref = baseConfig["editor-tagfilter-defaults"]) != null ? ref.filters : void 0) || [];
    if (!filters) {
      return;
    }
    for (i = 0, len = filters.length; i < len; i++) {
      filter = filters[i];
      mask_name = (ref1 = ez5.mask.CURRENT._mask_by_id[filter.mask_id]) != null ? ref1.name : void 0;
      if (!mask_name) {
        console.warn("EditorTagfilterDefaults: Unable to load mask", filter);
        continue;
      }
      if (!filter["default"] || filter.operation.length === 0) {
        continue;
      }
      if (!filters_by_mask_name[mask_name]) {
        filters_by_mask_name[mask_name] = [];
      }
      filters_by_mask_name[mask_name].push(filter);
      if (filter.tagfilter) {
        if (CUI.util.isString(filter.tagfilter)) {
          filter.tagfilter = JSON.parse(filter.tagfilter);
        }
      } else {
        filter.tagfilter = null;
      }
      if (filter.pool_id) {
        if (CUI.util.isString(filter.pool_id)) {
          filter.pool_id = JSON.parse(filter.pool_id);
        }
      } else {
        filter.pool_id = {
          ids: []
        };
      }
      filter["default"] = JSON.parse(filter["default"]);
    }
    listenTypes = ["editor-load", "editor-tags-field-changed", "pool-field-changed"];
    if (ez5.version("5.145")) {
      listenTypes.push("editor-mask-changed");
    }
    return CUI.Events.listen({
      type: listenTypes,
      call: (function(_this) {
        return function(ev, info) {
          var applyFilters, object, objectPool, operation, ref2, ref3;
          if (!info.editor_data) {
            return;
          }
          applyFilters = filters_by_mask_name[info.editor_data.mask_name];
          if (!applyFilters) {
            return;
          }
          object = info.object || info.new_object;
          if (!object) {
            return;
          }
          switch (info.editor.getMode()) {
            case "bulk":
              return;
            case "new":
              operation = "insert";
              break;
            case "single":
              operation = "update";
              if (ev.getType() === "editor-load") {
                return;
              }
          }
          applyFilters = applyFilters.filter(function(applyFilter) {
            var ref2;
            return indexOf.call(applyFilter.operation, operation) >= 0 && ((ref2 = applyFilter["default"]) != null ? ref2.length : void 0) > 0;
          });
          objectPool = info.new_pool || ((ref2 = info.editor_data) != null ? ref2._pool : void 0);
          if (applyFilters.length > 0) {
            _this.applyFilters(object, objectPool, applyFilters);
            if ((ref3 = info.editor) != null) {
              ref3.reloadEditor();
            }
          }
        };
      })(this)
    });
  };

  EditorTagfilterDefaults.prototype.applyFilters = function(object, objectPool, applyFilters) {
    var _, applyFilter, data, field, fields, filterByField, filterPoolId, filtersByField, find_field, i, idx, j, k, l, len, len1, len2, len3, len4, m, matchPool, matchRules, ref, ref1, rule, tagfilter_ok, unmatchedRules;
    data = object.getData();
    fields = object.mask.getFields("all");
    filtersByField = {};
    find_field = (function(_this) {
      return function(column_id) {
        var field, i, len;
        for (i = 0, len = fields.length; i < len; i++) {
          field = fields[i];
          if (field instanceof MaskSplitter) {
            continue;
          }
          if (field.id() === column_id) {
            return field;
          }
        }
      };
    })(this);
    for (i = 0, len = applyFilters.length; i < len; i++) {
      applyFilter = applyFilters[i];
      tagfilter_ok = TagFilter.matchesTags(applyFilter.tagfilter.tagfilter, data._tags);
      if (applyFilter.pool_id.ids.length > 0 && objectPool) {
        matchPool = false;
        ref = applyFilter.pool_id.ids;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          filterPoolId = ref[j];
          if (parseInt(filterPoolId) === objectPool.pool._id) {
            matchPool = true;
            break;
          }
        }
        if (!matchPool) {
          continue;
        }
      }
      ref1 = applyFilter["default"];
      for (idx = k = 0, len2 = ref1.length; k < len2; idx = ++k) {
        rule = ref1[idx];
        rule._idx = idx;
        rule._tagfilter_match = tagfilter_ok;
        rule._tagfilter = applyFilter.tagfilter.tagfilter;
        switch (rule.action) {
          case "preset":
            field = find_field(rule.column_id);
            if (!field) {
              console.error("EditorTagfilterDefaults: Skipping unknown field: " + rule.column_id);
              continue;
            }
            if (!filtersByField[field.id()]) {
              filtersByField[field.id()] = {
                field: field,
                rules: []
              };
            }
            filtersByField[field.id()].rules.push(rule);
            break;
          default:
            console.error("EditorTagfilterDefaults: Skipping unknown action: " + rule.action);
        }
      }
    }
    for (_ in filtersByField) {
      filterByField = filtersByField[_];
      matchRules = filterByField.rules.filter(function(rule) {
        return rule._tagfilter_match;
      });
      unmatchedRules = filterByField.rules.filter(function(rule) {
        return !rule._tagfilter_match;
      });
      if (unmatchedRules.length === filterByField.rules.length) {
        for (l = 0, len3 = unmatchedRules.length; l < len3; l++) {
          rule = unmatchedRules[l];
          if (filterByField.field instanceof DateColumn && rule.modifier) {
            rule = this.replaceDateRule(rule, filterByField.field);
          }
          filterByField.field.emptyEditorInputValue(rule.value, data);
        }
        continue;
      }
      for (m = 0, len4 = matchRules.length; m < len4; m++) {
        rule = matchRules[m];
        if (filterByField.field instanceof DateColumn && rule.modifier) {
          rule = this.replaceDateRule(rule, filterByField.field);
        }
        if (data._template && !rule._tagfilter) {
          filterByField.field.updateEditorInputValue(rule.value, data._template);
        } else {
          filterByField.field.updateEditorInputValue(rule.value, data);
        }
      }
    }
  };

  EditorTagfilterDefaults.prototype.replaceDateRule = function(rule, field) {
    if (indexOf.call(rule.modifier, "today") >= 0) {
      if (field instanceof DateTimeColumn) {
        rule.value = CUI.DateTime.format((new Date()).toISOString(), "display_short");
      } else {
        rule.value = CUI.DateTime.format((new Date()).toISOString().substr(0, 10), "display_short");
      }
    }
    return rule;
  };

  return EditorTagfilterDefaults;

})(CUI.Element);

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

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

  BaseConfigEditorTagfilterDefaults.prototype.getFieldDefFromParm = function(baseConfig, pname, def) {
    var field, getPresetOptions, get_mask_name, get_ot_name, i, idMask, last_ot_name, len, mask, mask_ids, mask_name, mask_opts, options, ot_name, tagFilter, toggleTagFilter, toggleUpdateOperation;
    toggleUpdateOperation = function(data, form) {
      var fieldData, nPoolIds, operationField, parentForm, ref, ref1, tagFilterField;
      parentForm = form.getForm() || form;
      fieldData = data["tagfilter"]["tagfilter"];
      tagFilterField = parentForm.getFieldsByName("tagfilter")[0];
      operationField = parentForm.getFieldsByName("operation")[0];
      nPoolIds = (data != null ? (ref = data.pool_id) != null ? (ref1 = ref.ids) != null ? ref1.length : void 0 : void 0 : void 0) || 0;
      if (nPoolIds > 0) {
        return operationField.enableOption("update");
      } else if (CUI.util.isEmpty(fieldData) || tagFilterField.isDisabled()) {
        return operationField.disableOption("update");
      } else {
        return operationField.enableOption("update");
      }
    };
    getPresetOptions = function(mask_id) {
      var field, i, len, mask, options, ref, validField;
      validField = function(field) {
        if (field instanceof TextColumn) {
          return true;
        }
        if (field instanceof DateColumn && !(field instanceof DateRangeColumn)) {
          return true;
        }
        if (field instanceof BooleanColumn) {
          return true;
        }
        return false;
      };
      mask = ez5.mask.CURRENT._mask_instance_by_name[ez5.mask.CURRENT._mask_by_id[mask_id].name];
      options = [];
      ref = mask.getFields("editor");
      for (i = 0, len = ref.length; i < len; i++) {
        field = ref[i];
        if (validField(field)) {
          options.push({
            text: field.nameLocalized(),
            value: field.id(),
            _field: field
          });
        }
      }
      return options;
    };
    switch (def.plugin_type) {
      case "mask-select":
        mask_ids = [];
        get_ot_name = function(mask_id) {
          return ez5.schema.CURRENT._table_by_id[ez5.mask.CURRENT._mask_by_id[mask_id].table_id]._name_localized;
        };
        get_mask_name = function(mask_id) {
          return ez5.mask.CURRENT._mask_by_id[mask_id]._name_localized;
        };
        mask_ids = (function() {
          var i, len, ref, results;
          ref = ez5.mask.CURRENT.masks;
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            mask = ref[i];
            if (!mask._instance) {
              results.push(mask.mask_id);
            }
          }
          return results;
        })();
        mask_ids.sort(function(a, b) {
          var a_mask_name, a_ot_name, b_mask_name, b_ot_name;
          a_ot_name = get_ot_name(a);
          b_ot_name = get_ot_name(b);
          if (a_ot_name === b_ot_name) {
            a_mask_name = get_mask_name(a);
            b_mask_name = get_mask_name(b);
            return CUI.util.compareIndex(a_mask_name.toLocaleLowerCase(), b_mask_name.toLocaleLowerCase());
          }
          return CUI.util.compareIndex(a_ot_name.toLocaleLowerCase(), b_ot_name.toLocaleLowerCase());
        });
        mask_opts = [];
        last_ot_name = null;
        for (i = 0, len = mask_ids.length; i < len; i++) {
          idMask = mask_ids[i];
          options = getPresetOptions(idMask);
          if (options.length === 0) {
            continue;
          }
          ot_name = get_ot_name(idMask);
          mask_name = get_mask_name(idMask);
          if (last_ot_name !== ot_name) {
            mask_opts.push({
              label: ot_name
            });
            last_ot_name = ot_name;
          }
          mask_opts.push({
            text: mask_name,
            text_selected: ot_name + ": " + mask_name,
            value: idMask
          });
        }
        toggleTagFilter = (function(_this) {
          return function(select, data) {
            var form, hasTags, ref, tagfilter;
            idMask = data[pname];
            mask = ez5.mask.CURRENT._mask_by_id[idMask];
            if (!mask) {
              return;
            }
            form = select.getForm().getForm();
            tagfilter = form.getFieldsByName("tagfilter")[0];
            hasTags = (ref = ez5.schema.CURRENT._table_by_id[mask.table_id]) != null ? ref.has_tags : void 0;
            if (hasTags) {
              return tagfilter.enable();
            } else {
              return tagfilter.disable();
            }
          };
        })(this);
        field = {
          type: CUI.Form,
          onRender: (function(_this) {
            return function(form) {
              return toggleUpdateOperation(form.getData(), form);
            };
          })(this),
          fields: [
            {
              type: CUI.Select,
              options: mask_opts,
              name: pname,
              onDataInit: (function(_this) {
                return function(select, data) {
                  return toggleTagFilter(select, data);
                };
              })(this),
              onDataChanged: function(_, select) {
                toggleTagFilter(select, select.getData());
                return toggleUpdateOperation(select.getData(), select.getForm());
              }
            }, {
              type: CUI.FormButton,
              appearance: "flat",
              icon: ez5.loca.get_key("editor.tagfilter.defaults.replacement.button|icon"),
              text: ez5.loca.get_key("editor.tagfilter.defaults.replacement.button|text"),
              tooltip: {
                text: ez5.loca.get_key("editor.tagfilter.defaults.replacement.button|tooltip")
              },
              onClick: (function(_this) {
                return function(ev, button) {
                  var base, key, mask_inst, rec, repl, ro;
                  mask = ez5.mask.CURRENT._mask_by_id[button.getData()[pname]];
                  if (!mask) {
                    return;
                  }
                  mask_inst = ez5.mask.CURRENT._mask_instance_by_name[mask.name];
                  ro = new ResultObjectDemo({
                    mask: mask_inst,
                    format: "long",
                    format_linked_object: "standard"
                  });
                  rec = mask_inst.getReplacementRecord(ro.getData());
                  repl = [];
                  for (key in rec) {
                    repl.push("%" + key + "%");
                  }
                  if (typeof (base = ez5.session).getReplacementRecord === "function" ? base.getReplacementRecord() : void 0) {
                    for (key in ez5.session.getReplacementRecord()) {
                      repl.push("%" + key + "%");
                    }
                  }
                  return new CUI.Tooltip({
                    on_click: true,
                    element: button,
                    "class": "ez5-editor-tagfilter-defaults-replacements-help",
                    text: repl.join("\n")
                  }).show();
                };
              })(this)
            }
          ]
        };
        break;
      case "column-default-value":
        field = {
          type: CUI.DataTable,
          maximize_horizontal: true,
          name: pname,
          onDataInit: (function(_this) {
            return function(_, data) {
              if (!data[pname] || !CUI.util.isArray(data[pname])) {
                return data[pname] = [];
              }
            };
          })(this),
          fields: [
            {
              form: {
                label: $$(baseConfig.locaKey("parameter") + ".type.label")
              },
              type: CUI.Select,
              name: "action",
              options: [
                {
                  text: $$(baseConfig.locaKey("option") + ".type.preset"),
                  value: "preset"
                }
              ]
            }, {
              form: {
                label: $$(baseConfig.locaKey("parameter") + ".column_id.label")
              },
              type: CUI.Select,
              name: "column_id",
              onDataChanged: (function(_this) {
                return function(_, selectField) {
                  return selectField.getForm().getFieldsByName("data-field-proxy")[0].reload();
                };
              })(this),
              options: (function(_this) {
                return function(df) {
                  var mask_id;
                  mask_id = df.getForm().getDataTable().getData().mask_id;
                  CUI.util.assert(mask_id > 0, "EditorTagfilterDefaults.column-default-value", "Unable to get mask_id from data table data.", {
                    dataField: df
                  });
                  if (ez5.mask.CURRENT._mask_by_id[mask_id]) {
                    return getPresetOptions(mask_id);
                  } else {
                    return [];
                  }
                };
              })(this)
            }, {
              type: CUI.DataFieldProxy,
              call_others: false,
              form: {
                label: $$(baseConfig.locaKey("parameter") + ".value.label")
              },
              name: "data-field-proxy",
              element: (function(_this) {
                return function(dataField) {
                  var checkbox, data, dateTime, findField, multiInput, numberInput, proxyInput, ref, selectOptions;
                  selectOptions = (ref = dataField.getForm().getFieldsByName("column_id")[0]) != null ? ref.getOptions() : void 0;
                  data = dataField.getData();
                  findField = function() {
                    var j, len1, option;
                    for (j = 0, len1 = selectOptions.length; j < len1; j++) {
                      option = selectOptions[j];
                      if (option.value === data.column_id) {
                        return option._field;
                      }
                    }
                  };
                  dataField = findField();
                  if (dataField instanceof LocaTextColumn) {
                    if (!CUI.isPlainObject(data.value)) {
                      data.value = {};
                    }
                    multiInput = new CUI.MultiInput({
                      textarea: dataField instanceof LocaTextMultiColumn,
                      data: data,
                      name: "value",
                      control: ez5.loca.getLanguageControlAdmin()
                    });
                    return multiInput.start();
                  } else if (dataField instanceof NumberColumn) {
                    if (!CUI.util.isNumber(data.value)) {
                      delete data.value;
                    }
                    numberInput = new CUI.NumberInput({
                      data: data,
                      name: "value"
                    });
                    return numberInput.start();
                  } else if (dataField instanceof DateColumn) {
                    dateTime = dataField instanceof DateTimeColumn;
                    proxyInput = new CUI.DataFieldProxy({
                      element: function(dataField) {
                        var dateInput, hl;
                        options = new CUI.Options({
                          name: "modifier",
                          data: data,
                          options: [
                            {
                              text: $$(baseConfig.locaKey("parameter") + ".date.replacement.today|text"),
                              value: "today",
                              tooltip: {
                                text: $$(baseConfig.locaKey("parameter") + ".date.replacement.today|tooltip")
                              }
                            }
                          ],
                          onDataChanged: function() {
                            return dataField.reload();
                          }
                        });
                        if (indexOf.call(data.modifier, "today") >= 0) {
                          dateInput = null;
                        } else {
                          dateInput = new CUI.DateTime({
                            name: "value",
                            data: data,
                            input_types: dateTime ? ["date_time"] : ["date"]
                          });
                        }
                        hl = new CUI.HorizontalList({
                          maximize_horizontal: true,
                          content: [options, dateInput]
                        });
                        return hl;
                      }
                    });
                    return proxyInput.start();
                  } else if (dataField instanceof BooleanColumn) {
                    if (!CUI.util.isBoolean(data.value)) {
                      data.value = true;
                    }
                    checkbox = new CUI.Checkbox({
                      data: data,
                      name: "value"
                    });
                    return checkbox.start();
                  } else {
                    if (CUI.isPlainObject(data.value)) {
                      data.value = "";
                    }
                    numberInput = new CUI.Input({
                      textarea: dataField instanceof TextMultiColumn,
                      data: data,
                      name: "value"
                    });
                    return numberInput.start();
                  }
                };
              })(this)
            }
          ]
        };
        break;
      case "tag-filter":
        tagFilter = new TagFilter({
          tagForm: ez5.tagForm,
          name: pname
        });
        field = tagFilter.getField({
          onDataChanged: (function(_this) {
            return function(data, dataField) {
              var tagFilterData;
              tagFilterData = {
                tagfilter: data
              };
              return toggleUpdateOperation(tagFilterData, dataField.getForm());
            };
          })(this)
        });
        field.name = pname;
        break;
      case "pool-select":
        field = {
          type: CUI.DataFieldProxy,
          call_others: false,
          name: pname,
          element: (function(_this) {
            return function(dataField) {
              var formButton, getPoolBtnText, ref, ref1;
              getPoolBtnText = function(data) {
                var ref;
                if ((data != null ? (ref = data.ids) != null ? ref.length : void 0 : void 0) > 0) {
                  return $$("admin.message.pools.button.selected", {
                    count: data.ids.length
                  });
                } else {
                  return $$("admin.message.pools.button");
                }
              };
              formButton = new CUI.FormButton({
                text: getPoolBtnText(dataField.getData().pool_id),
                active: ((ref = dataField.getData().pool_id) != null ? (ref1 = ref.ids) != null ? ref1.length : void 0 : void 0) > 0,
                onClick: function() {
                  var cancelButton, doneButton, poolData, poolFormModal, temporalData;
                  poolData = function() {
                    return dataField.getData();
                  };
                  temporalData = CUI.util.copyObject(poolData().pool_id, true) || {};
                  _this.__pools_form = new PoolsForm({
                    data: temporalData,
                    treeOpts: {
                      "class": 'cui-lv--has-datafields',
                      maximize: false,
                      rowMove: false,
                      cols: ["auto"]
                    }
                  });
                  doneButton = new CUI.Button({
                    text: $$("base.done"),
                    primary: true,
                    onClick: function(ev) {
                      var ref2, ref3;
                      poolData().pool_id = _this.__pools_form.getSaveData();
                      poolFormModal.destroy();
                      formButton.setText(getPoolBtnText(dataField.getData().pool_id));
                      if (((ref2 = dataField.getData().pool_id) != null ? (ref3 = ref2.ids) != null ? ref3.length : void 0 : void 0) > 0) {
                        formButton.activate();
                      } else {
                        formButton.deactivate();
                      }
                      CUI.Events.trigger({
                        node: formButton,
                        type: "data-changed"
                      });
                      return toggleUpdateOperation(dataField.getData(), dataField.getForm());
                    }
                  });
                  cancelButton = new CUI.Button({
                    text: $$("base.abort"),
                    onClick: function(ev) {
                      return poolFormModal.destroy();
                    }
                  });
                  poolFormModal = new CUI.Modal({
                    "class": "cui-pools-form",
                    cancel: true,
                    pane: {
                      header_left: new CUI.Label({
                        text: $$("admin.message.pools.pools_form.title")
                      }),
                      content: _this.__pools_form.renderForm(),
                      footer_right: [cancelButton, doneButton]
                    },
                    onDestroy: function() {
                      if (typeof onClose === "function") {
                        onClose();
                      }
                    }
                  });
                  return poolFormModal.show();
                }
              });
              return formButton.start();
            };
          })(this)
        };
    }
    return field;
  };

  return BaseConfigEditorTagfilterDefaults;

})(BaseConfigPlugin);

ez5.defaults_done(function() {
  return new EditorTagfilterDefaults();
});
