// Generated by CoffeeScript 1.12.7

/*
  TODO TODO # TODO:

  bestehende Probleme:
  - wenn in einem Wiederholblock keine felder mehr sind, soll der ganze block weg sein, auch der Plus-Button etc..
 */
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,
  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; };

ez5.EditorFieldVisibility = (function(superClass) {
  extend(EditorFieldVisibility, superClass);

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

  EditorFieldVisibility.prototype.isSimpleSplit = function() {
    return false;
  };

  EditorFieldVisibility.prototype.isEnabledForNested = function() {
    return true;
  };

  EditorFieldVisibility.prototype.__getFieldNamesFieldConcordanceFromFieldList = function(fieldList) {
    var attrname, entryKey, field, fieldsToReturn, i, len, nextLevelFieldsToReturn, ref, ref1, ref2, val;
    fieldsToReturn = {};
    for (i = 0, len = fieldList.length; i < len; i++) {
      field = fieldList[i];
      if (field.__cls === 'NestedRow') {
        field = field._field;
      }
      if ((field != null ? (ref = field.FieldSchema) != null ? ref.kind : void 0 : void 0) === 'field' || (field != null ? (ref1 = field.FieldSchema) != null ? ref1.kind : void 0 : void 0) === 'link') {
        entryKey = field['FieldSchema']['_full_name'];
        fieldsToReturn[entryKey] = field;
      }
      if ((field != null ? (ref2 = field.FieldSchema) != null ? ref2.kind : void 0 : void 0) === 'linked-table') {
        entryKey = field['FieldSchema']['_full_name'];
        fieldsToReturn[entryKey] = field;
        nextLevelFieldsToReturn = this.__getFieldNamesFieldConcordanceFromFieldList(field.mask.fields);
        for (attrname in nextLevelFieldsToReturn) {
          val = nextLevelFieldsToReturn[attrname];
          fieldsToReturn[attrname] = nextLevelFieldsToReturn[attrname];
        }
      }
    }
    return fieldsToReturn;
  };

  EditorFieldVisibility.prototype.__getListOfFieldNamesInsideSplitter = function(fieldList) {
    var entry, key, list, resultList;
    list = this.__getFieldNamesFieldConcordanceFromFieldList(fieldList);
    resultList = [];
    for (key in list) {
      entry = list[key];
      resultList.push(key);
    }
    return resultList;
  };

  EditorFieldVisibility.prototype.__getFlatListOfAffectedSplitterFields = function(optsData, prefix) {
    var cleanedFieldName, field, fieldEntry, fieldList, fieldName, fieldNameParts, fieldType, fields, i, isCustomType, lastPartOfFieldName, len, newPrefix;
    if (prefix == null) {
      prefix = '';
    }
    fieldList = [];
    for (fieldName in optsData) {
      field = optsData[fieldName];
      if (!fieldName.startsWith('_version')) {
        if ((fieldName.indexOf('_nested:') > -1) && (fieldName.indexOf(':rendered') > -1)) {
          cleanedFieldName = fieldName.replace(/_nested:/g, '');
          cleanedFieldName = cleanedFieldName.replace(/:rendered/g, '');
          if (prefix !== '') {
            fieldName = prefix + '.' + cleanedFieldName;
          } else {
            fieldName = cleanedFieldName;
          }
          fieldName = this.objecttype + '.' + fieldName;
          if (this.splitterFieldNames.indexOf(fieldName) !== -1) {
            fieldList.push({
              'name': fieldName,
              'field': field,
              'element': field.getElement()
            });
          } else {
            fieldList.push({
              'name': fieldName,
              'field': field,
              'element': field.getElement(),
              'type': 'block'
            });
          }
        }
        if ((fieldName.indexOf('_nested:') > -1) && (fieldName.indexOf(':rendered') === -1)) {
          for (i = 0, len = field.length; i < len; i++) {
            fieldEntry = field[i];
            cleanedFieldName = fieldName.replace(/_nested:/g, '');
            if (prefix !== '') {
              newPrefix = prefix + '.' + cleanedFieldName;
            } else {
              newPrefix = cleanedFieldName;
            }
            fields = this.__getFlatListOfAffectedSplitterFields(fieldEntry, newPrefix);
            fieldList = fieldList.concat(fields);
          }
        }
        if (fieldName.indexOf('_nested:') === -1 && (fieldName.indexOf(':rendered') > -1)) {
          if (prefix !== '') {
            fieldName = prefix + '.' + fieldName.replace(':rendered', '');
          } else {
            fieldName = fieldName.replace(':rendered', '');
          }
          fieldName = field.opts.field.__dbg_full_name;
          fieldName = fieldName.replace(/_nested:/g, '');
          fieldNameParts = fieldName.split('.');
          lastPartOfFieldName = fieldNameParts.pop();
          if (this.splitterFieldNames.indexOf(fieldName) !== -1) {
            fieldType = field._field.ColumnSchema.type;
            if (fieldType.indexOf('custom-data-type') > 0) {
              isCustomType = true;
            } else {
              isCustomType = false;
            }
            fieldList.push({
              'dataTarget': lastPartOfFieldName,
              'dataReference': optsData,
              'name': fieldName,
              'field': field,
              'element': field.getElement(),
              'type': fieldType,
              'isCustomType': isCustomType
            });
          }
        }
      }
    }
    return fieldList;
  };

  EditorFieldVisibility.prototype.renderField = function(opts) {
    var columnType, fieldsKey, fieldsRendererPlain, fieldsValue, i, innerFields, innerSplitterFields, j, jsonMap, jsonMapEntry, jsonMapKey, jsonTargetPath, len, len1, observedField, observedFieldName, ref, ref1, ref2, ref3, splitterField, that;
    that = this;
    observedFieldName = (ref = this.getDataOptions()) != null ? ref.observedfield : void 0;
    if (!observedFieldName) {
      return;
    }
    this.objecttype = (ref1 = opts.top_level_data) != null ? ref1._objecttype : void 0;
    this.splitterFieldNames = [];
    innerFields = this.renderInnerFields(opts);
    if (opts.mode === "detail") {
      return innerFields;
    }
    jsonMap = this.getDataOptions().jsonmap;
    jsonTargetPath = this.getDataOptions().jsontargetpath;
    if (CUI.util.isEmpty(jsonMap)) {
      return innerFields;
    } else {
      jsonMap = JSON.parse(jsonMap);
    }
    for (jsonMapKey in jsonMap) {
      jsonMapEntry = jsonMap[jsonMapKey];
      ref2 = jsonMapEntry.fields;
      for (fieldsKey = i = 0, len = ref2.length; i < len; fieldsKey = ++i) {
        fieldsValue = ref2[fieldsKey];
        jsonMap[jsonMapKey].fields[fieldsKey] = jsonTargetPath + '.' + jsonMapEntry.fields[fieldsKey];
      }
    }
    fieldsRendererPlain = this.__customFieldsRenderer.fields[0];
    if (!(fieldsRendererPlain instanceof FieldsRendererPlain)) {
      return innerFields;
    }
    innerSplitterFields = fieldsRendererPlain.getFields() || [];
    if (!innerSplitterFields) {
      return innerFields;
    }
    this.splitterFieldNames = this.__getListOfFieldNamesInsideSplitter(innerSplitterFields);
    ref3 = this.__getFlatListOfAffectedSplitterFields(opts.data);
    for (j = 0, len1 = ref3.length; j < len1; j++) {
      splitterField = ref3[j];
      if (splitterField.name === observedFieldName) {
        columnType = splitterField.type;
        observedField = splitterField.field;
      }
    }
    CUI.Events.listen({
      type: ["data-changed"],
      node: innerFields[0],
      call: (function(_this) {
        return function(ev, info) {
          return _this.__manageVisibilitys(opts, columnType, observedField, jsonMap, observedFieldName);
        };
      })(this)
    });
    CUI.Events.listen({
      type: ["editor-changed"],
      call: (function(_this) {
        return function(ev, info) {
          return _this.__manageVisibilitys(opts, columnType, observedField, jsonMap, observedFieldName);
        };
      })(this)
    });
    this.__manageVisibilitys(opts, columnType, observedField, jsonMap, observedFieldName);
    return innerFields;
  };

  EditorFieldVisibility.prototype.__manageVisibilitys = function(opts, columnType, observedField, jsonMap, observedFieldName) {
    var actionField, actionFields, dataAsJson, dataAsString, globalObjId, i, idParts, j, jsonMapEntryName, jsonMapValue, jsonMatchedMappingFields, k, len, len1, len2, observedFieldValue, observedFieldValueObject, observedFieldValueString, ref, ref1, results, results1, that;
    that = this;
    observedFieldValue = '';
    actionFields = [];
    actionFields = this.__getFlatListOfAffectedSplitterFields(opts.data);
    if (columnType === 'custom:base.custom-data-type-dante.dante') {
      dataAsString = observedField._field.getDataAsString(observedField._data, observedField._top_level_data);
      if (!CUI.util.isEmpty(dataAsString)) {
        dataAsJson = JSON.parse(dataAsString);
        observedFieldValue = dataAsJson.conceptURI;
        if (observedFieldValue) {
          observedFieldValue = observedFieldValue.replace('https', 'http');
        }
      } else {
        observedFieldValue = null;
      }
    }
    if (columnType === 'boolean') {
      observedFieldValue = observedField._field.getDataAsString(observedField._data, observedField._top_level_data);
      if (observedFieldValue === '') {
        observedFieldValue = 'false';
      }
    }
    if (columnType === 'link') {
      observedFieldValueString = observedField._field.getDataAsString(observedField._data, observedField._top_level_data);
      if (observedFieldValueString) {
        observedFieldValueObject = JSON.parse(observedFieldValueString);
        globalObjId = observedFieldValueObject != null ? observedFieldValueObject._global_object_id : void 0;
        idParts = globalObjId.split('@');
        observedFieldValue = idParts[0];
      }
    }
    if (CUI.util.isEmpty(observedFieldValue)) {
      results = [];
      for (i = 0, len = actionFields.length; i < len; i++) {
        actionField = actionFields[i];
        if (actionField.name !== observedFieldName) {
          if (observedFieldName.indexOf(actionField.name) === -1 || actionField.type !== 'block') {
            results.push(that.hideAndClearActionField(actionField));
          } else {
            results.push(void 0);
          }
        } else {
          results.push(void 0);
        }
      }
      return results;
    } else {
      jsonMatchedMappingFields = false;
      for (jsonMapEntryName in jsonMap) {
        jsonMapValue = jsonMap[jsonMapEntryName];
        if ((jsonMapValue != null ? (ref = jsonMapValue.value) != null ? ref.trim() : void 0 : void 0) === observedFieldValue) {
          if (jsonMapValue != null ? jsonMapValue.fields : void 0) {
            jsonMatchedMappingFields = jsonMapValue.fields;
            break;
          }
        }
      }
      if (((ref1 = this.getDataOptions()) != null ? ref1.helpwithactionfieldnames : void 0) === 1) {
        console.warn("List of actionfield-path-names inside the splitter:");
        for (j = 0, len1 = actionFields.length; j < len1; j++) {
          actionField = actionFields[j];
          if (actionField.name !== observedFieldName) {
            console.log(actionField.name);
          }
        }
      }
      results1 = [];
      for (k = 0, len2 = actionFields.length; k < len2; k++) {
        actionField = actionFields[k];
        if (actionField.name !== observedFieldName) {
          if (jsonMatchedMappingFields) {
            if (jsonMatchedMappingFields.indexOf(actionField.name) !== -1 || jsonMatchedMappingFields.includes(actionField.name) !== false) {
              results1.push(that.hideAndClearActionField(actionField));
            } else {
              results1.push(CUI.dom.showElement(actionField.element));
            }
          } else {
            results1.push(CUI.dom.showElement(actionField.element));
          }
        } else {
          results1.push(void 0);
        }
      }
      return results1;
    }
  };

  EditorFieldVisibility.prototype.hideAndClearActionField = function(actionField) {
    var customDataTypes, deletionValue, domData, domInput, easyTypes, i, input, j, len, len1, node, ref, ref1, ref2, rowType;
    domInput = CUI.dom.matchSelector(actionField.element, ".cui-data-field")[0];
    domData = CUI.dom.data(domInput, "element");
    if (domData) {
      rowType = domData.constructor.name;
    } else {
      rowType = '';
    }
    CUI.dom.hideElement(actionField.element);
    if (domData || actionField.isCustomType) {
      if (actionField != null ? actionField.dataReference : void 0) {
        if (actionField.dataReference[actionField.dataTarget]) {
          if (typeof actionField.dataReference[actionField.dataTarget] === 'object') {
            for (deletionValue in actionField.dataReference[actionField.dataTarget]) {
              if (actionField.dataReference[actionField.dataTarget][deletionValue]) {
                if (actionField.type === 'text_l10n' || actionField.type === 'text_l10n_oneline') {
                  actionField.dataReference[actionField.dataTarget][deletionValue] = '';
                } else {
                  delete actionField.dataReference[actionField.dataTarget][deletionValue];
                }
              }
            }
          }
        }
      }
      easyTypes = {
        'Input': '',
        'Checkbox': false,
        'DateTime': '',
        'NumberInput': null
      };
      if (rowType in easyTypes) {
        domData.setValue(easyTypes[rowType]);
      }
      if (rowType === 'MultiInput') {
        ref = domData.__inputs;
        for (i = 0, len = ref.length; i < len; i++) {
          input = ref[i];
          input.setValue('');
        }
      }
      if (actionField.type === 'daterange') {
        ref1 = domData.getFields();
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          input = ref1[j];
          input.setValue('');
        }
      }
      customDataTypes = ['custom:base.custom-data-type-dante.dante', 'custom:base.custom-data-type-geonames.geonames', 'custom:base.custom-data-type-getty.getty', 'custom:base.custom-data-type-gnd.gnd', 'custom:base.custom-data-type-gn250.gn250', 'custom:base.custom-data-type-georef.georef', 'custom:base.custom-data-type-gazetteer.gazetteer', 'custom:base.custom-data-type-iconclass.iconclass', 'custom:base.custom-data-type-link.link', 'custom:base.custom-data-type-gvk.gvk', 'custom:base.custom-data-type-nomisma.nomisma'];
      if (ref2 = actionField.type, indexOf.call(customDataTypes, ref2) >= 0) {
        actionField.field.setChanges();
        actionField.field.initOpts();
        if (domData) {
          domData.unsetData();
        }
        node = CUI.dom.matchSelector(actionField.element, ".customPluginEditorLayout");
        if (!node) {
          node = CUI.dom.matchSelector(actionField.element, ".dante_InlineSelect");
        }
        if (node) {
          CUI.Events.registerEvent({
            type: "custom-deleteDataFromPlugin",
            bubble: false
          });
          CUI.Events.trigger({
            type: 'custom-deleteDataFromPlugin',
            node: node[0],
            bubble: false
          });
        }
      }
      if ((!actionField.isCustomType || domData) && actionField.type !== 'text_l10n' && actionField.type !== 'text_l10n_oneline') {
        if (domData) {
          return domData.displayValue();
        }
      }
    }
  };

  EditorFieldVisibility.prototype.__getOptionsFromLinkedTable = function(linkedField) {
    var field, i, len, newOptions, ref;
    newOptions = [];
    ref = linkedField.mask.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field.kind === 'field') {
        newOptions.push(this.__getOptionFromField(field));
      }
      if (field.kind === 'link') {
        newOptions.push(this.__getOptionFromField(field));
      }
      if (field.kind === 'linked-table') {
        newOptions = newOptions.concat(this.__getOptionsFromLinkedTable(field));
      }
    }
    return newOptions;
  };

  EditorFieldVisibility.prototype.__getOptionFromField = function(field, complex) {
    var newOption;
    newOption = {
      value: field._full_name,
      text: field._column._name_localized + ' [' + field.column_name_hint + '] ("' + field._full_name + '")'
    };
    return newOption;
  };

  EditorFieldVisibility.prototype.getOptions = function() {
    var field, fieldOptions, fields, i, len, maskOptions, ref, test, that;
    that = this;
    fieldOptions = [];
    if ((ref = this.opts) != null ? ref.maskEditor : void 0) {
      fields = this.opts.maskEditor.opts.schema.fields;
      for (i = 0, len = fields.length; i < len; i++) {
        field = fields[i];
        if (field.kind === 'field') {
          fieldOptions.push(this.__getOptionFromField(field));
        }
        if (field.kind === 'link') {
          console.log(field);
          fieldOptions.push(this.__getOptionFromField(field));
        }
        if (field.kind === 'linked-table') {
          test = this.__getOptionsFromLinkedTable(field);
          fieldOptions = fieldOptions.concat(test);
        }
      }
    }
    maskOptions = [
      {
        form: {
          label: $$('editor.field.visibility.nameofobservedfield')
        },
        type: CUI.Select,
        name: "observedfield",
        options: fieldOptions
      }, {
        form: {
          label: $$('editor.field.visibility.targetpath')
        },
        type: CUI.Input,
        name: "jsontargetpath"
      }, {
        form: {
          label: $$('editor.field.visibility.map')
        },
        type: CUI.Input,
        name: "jsonmap"
      }, {
        form: {
          label: $$('editor.field.visibility.helpwithactionfieldnames')
        },
        type: CUI.Select,
        undo_and_changed_support: false,
        name: 'helpwithactionfieldnames',
        empty_text: $$('editor.field.visibility.helpwithactionfieldnames_no'),
        options: (function(_this) {
          return function(thisSelect) {
            var itemNo, itemYes, select_items;
            select_items = [];
            itemNo = {
              text: $$('editor.field.visibility.helpwithactionfieldnames_no'),
              value: 0
            };
            select_items.push(itemNo);
            itemYes = {
              text: $$('editor.field.visibility.helpwithactionfieldnames_yes'),
              value: 1
            };
            select_items.push(itemYes);
            return select_items;
          };
        })(this)
      }
    ];
    return maskOptions;
  };

  EditorFieldVisibility.prototype.trashable = function() {
    return true;
  };

  return EditorFieldVisibility;

})(CustomMaskSplitter);

CUI.ready((function(_this) {
  return function() {
    return MaskSplitter.plugins.registerPlugin(ez5.EditorFieldVisibility);
  };
})(this));
