import moment from 'moment';

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',
    },
    ['After']: {
      id: 'after',
      displayName: 'After',
      prefix: 'After ',
      buildItem: (value) => {
        const option = 'after';
        return (value ? { value, label: value.format('MM-DD-YYYY'), option } : { option });
      },
    },
    ['Before']: {
      id: 'before',
      displayName: 'Before',
      prefix: 'Before ',
      buildItem: (value) => {
        const option = 'before';
        return (value ? { value, label: value.format('MM-DD-YYYY'), option } : { option });
      },
    },
    ['Between']: {
      id: 'between',
      displayName: 'Between',
      buildItem: (value) => (
        { value, label: `${value[0].format('MM-DD-YYYY')} - ${value[1].format('MM-DD-YYYY')}`, option: 'between' }
      ),
    },
    ['Today']: {
      id: 'today',
      displayName: 'Today',
      loadDefaultValue() {
        this.selected = this.displayName;
        return true;
      }
    },
  }
};

export default OptionFactory;

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

export const defaultOptions = ['Any', 'After', 'Before', 'Between', 'Today'];
