const baseProto = {
  buildItem(data) {
    const value = data.target ? data.target.value : data;

    return value ? { value, label: String(value), option: this.id } : { option: this.id };
  },

  set selected(value) {
    this.selectedObject = this.buildItem(value);
    if (this.selectedObject) {
      this.selectedObject.chickletLabel = this.chickletLabel(this.selectedObject.label);
    }
  },

  get selected() {
    return this.selectedObject;
  },

  get selectedLabel() {
    return this.selectedObject ? this.selectedObject.label : '';
  },

  get selectedValue() {
    return this.selectedObject ? this.selectedObject.value : '';
  },

  loadDefaultValue() {
    return null;
  },

  chickletLabel(value) {
    const prefix = this.prefix || '';
    return prefix + String(value);
  },
};

const OptionFactory = {
  create(type) {
    return Object.assign(
      Object.create(baseProto),
      this.optionsMap[type],
      { key: type },
    );
  },

  optionsMap: {
    Any: {
      id: 'any',
      displayName: 'Any',
    },
    EqualTo: {
      id: 'eq',
      displayName: 'Equal To',
    },
    NotEqualTo: {
      id: 'neq',
      displayName: 'Not Equal To',
      prefix: '!=',
    },
    GreaterThan: {
      id: 'gt',
      displayName: 'Grater Than',
      prefix: '>',
    },
    GreaterThanOrEqualTo: {
      displayName: 'Grater Than Or Equal To',
      id: 'gteq',
      prefix: '>=',
    },
    LessThan: {
      id: 'lt',
      displayName: 'Less Than',
      prefix: '<',
    },
    LessThanOrEqualTo: {
      id: 'lteq',
      displayName: 'Less Than Or Equal To',
      prefix: '<=',
    },
    SpecifyARange: {
      id: 'range',
      displayName: 'Specify A Range',
      buildItem: value => ({ value, label: `${value[0]}-${value[1]}`, option: 'range' }),
    },
    None: {
      id: 'none',
      displayName: 'None',
      loadDefaultValue() {
        this.selectedValue = 'None';
        return true;
      },
    },
    MoreThanZero: {
      id: 'mtz',
      displayName: 'More Than 0',
      loadDefaultValue() {
        this.selected = 'More Than 0';
        return true;
      },
    },
  },
};

export default OptionFactory;

export function isValidOption(option) {
  return Object.keys(OptionFactory.optionsMap).indexOf(option) >= 0;
}

export const defaultOptions = ['Any', 'EqualTo', 'GreaterThanOrEqualTo', 'LessThanOrEqualTo', 'SpecifyARange'];

export function buildCustomOption({ value, label }) {
  return Object.assign(
    Object.create(baseProto),
    {
      id: `custom-${label}`,
      displayName: label,
      key: `custom-${label}`,
      loadDefaultValue() {
        this.selected = value;
      },
    },
  );
}
