import moment from 'moment';
import getProcoreLocale from './getProcoreLocale';

const getCalendarIsRange = (dates) => {
  const isRange = dates && dates.length === 2;

  return isRange;
};

const getFormattedDates = (dates) => {
  const formattedDates = [];

  dates.map((date) => {
    if (Object.keys(date).length > 0) {
      formattedDates.push(moment(date).format('L'));
    } else {
      formattedDates.push('');
    }
  });

  return formattedDates;
};

const getMomentDates = (dates, locale) => {
  let momentDates = [];

  if (dates.length === 0) {
    momentDates = [{}, {}];
  } else {
    dates.map((date) => {
      if (date === '') {
        momentDates.push({});
      } else {
        // TODO: Move locale setting code to componentDidMount so only run it once
        moment.locale(getProcoreLocale(locale));
        momentDates.push(moment(date, 'YYYY-MM-DD HH:mm:ss Z'));
      }
    });
  }

  return momentDates;
};

const isDateValid = (dates, index) => !!dates[index] && Object.keys(dates[index]).length > 0;

const isValidcommittedDates = (filter) => {
  const commitedStartDate = (filter && filter[0] && filter[0] !== '') ? filter[0] : null;
  const commitedEndDate = (filter && filter[1] && filter[1] !== '') ? filter[1] : null;
  const isRange = getCalendarIsRange(filter);

  if (
    (isRange && commitedStartDate && commitedEndDate) ||
    (!isRange && commitedStartDate && !commitedEndDate)
  ) {
    return true;
  }

  return false;
};

export {
  getFormattedDates,
  getMomentDates,
  isDateValid,
  isValidcommittedDates
};
