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

const baseProto = {
  buildItem({ value, label }) {
    return value ? { value, 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(label) {
    const prefix = this.prefix || '';
    return prefix + String(label);
  },
};

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

  optionsMap: {
    [ANY]: {
      id: ANY,
      displayName: ANY,
      position: FIRST_POSITION,
    },
    [USER_SPECIFIED_OPTION]: {
      id: USER_SPECIFIED_OPTION,
      displayName: 'Enter a String(s)...',
      position: LAST_POSITION,
    },

  },
};

export default OptionFactory;

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

export const buildCustomOption = ({ value, label, category, position }) => {
  const pos = position ? position / 100 : MIDDLE_POSITION;
  return Object.assign(
    Object.create(baseProto),
    {
      id: String(value),
      displayName: label,
      key: value,
      category,
      position: pos,
      loadDefaultValue() {
        this.selected = { value, label };
        return true;
      },
    });
};
