class ConditionalDisplay {
  constructor(container, field, key, condition) {
    this.container = container;
    this.field = field;
    this.key = this.setKey(key);
    this.condition = condition;
    this.elements = [];
    this.setEvent();
  }

  setKey(key) {
    if (this.field == 'checkbox')
      return key + '[]';
    return key;
  }

  setEvent() {
    this.elements = Array.from(document.querySelectorAll(`[name="${this.key}"]`));
    if (this.elements.length > 0) {
      this.elements.forEach(el => el.addEventListener('change', this.display.bind(this)));
      this.display();
    }
  }

  getValue() {
    this.elements = Array.from(document.querySelectorAll(`[name="${this.key}"]`));

    var func = {
      'radio': () => {
        var field = this.elements.find(el => el.checked);
        return field.value;
      },
      'select': () => (this.elements[0].value),
      'input': () => (this.elements[0].value),
      'checkbox': () => {
        var fields = this.elements.filter(el => el.checked && el.value);
        return fields.map(f => f.value);
      }
    }
    return func[this.field] ? func[this.field]() : '';
  }

  display() {
    var value = this.getValue();

    if (this.field == 'checkbox') {
      if (value.indexOf(this.condition) !== -1)
        this.container.style.display = 'block';
      else
        this.container.style.display = 'none';
    } else {
      if (value == this.condition)
        this.container.style.display = 'block';
      else
        this.container.style.display = 'none';
    }

  }
}

export default ConditionalDisplay;