import {
  ANY,
  LAST_POSITION,
  FIRST_POSITION,
  MIDDLE_POSITION,
  CHICKLET_ORANGE,
  USER_SPECIFIED_OPTION,
} from '../../constants';

const baseProto = {
  buildItem({ values, label }) {
    return values
      ? { values, label, option: this.id, category: this.category }
      : { 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, selected) {
    return Object.assign(Object.create(baseProto), this.optionsMap[type], {
      key: type,
      isSelected: selected,
    });
  },

  setAnyDisplayName(name) {
    this.optionsMap[ANY].displayName = name;
  },

  setUserSpecifiedDisplayName(name) {
    this.optionsMap[USER_SPECIFIED_OPTION].displayName = name;
  },

  createCustom({ values, label, selected, category, position }) {
    const pos = position ? position / 100 : MIDDLE_POSITION;
    return Object.assign(Object.create(baseProto), {
      id: values.join(),
      displayName: label,
      key: values.join(),
      isSelected: selected,
      category,
      position: pos,
      loadDefaultValue() {
        this.selected = { values, label };
        return true;
      },
    });
  },

  optionsMap: {
    [ANY]: {
      id: ANY,
      displayName: ANY,
    },
    [USER_SPECIFIED_OPTION]: {
      id: USER_SPECIFIED_OPTION,
      displayName: 'Search...',
    },
  },
};

export default OptionFactory;

export const isValidOption = option => Object.keys(OptionFactory.optionsMap).indexOf(option) >= 0;
