import * as React from 'react';
import { FormattedDate, FormattedTime } from 'react-intl';

if (process.env.BROWSER) {
  require('./timespan.sass');
}

interface TimespanProps {
  start: Date;
  end: Date;
}

export function Timespan({
  start,
  end,
}: TimespanProps): React.ReactElement<{}> {
  if (isSameDay(new Date(start), new Date(end))) {
    return sameDayTimespan(start, end);
  } else {
    return differentDayTimespan(start, end);
  }
}

function sameDayTimespan(start: Date, end: Date): React.ReactElement<{}> {
  return (
    <span className="timespan--date">
      <FormattedDate
        value={start}
        weekday="long"
        month="short"
        day="numeric"
      />{' '}
      <FormattedTime value={start} /> - <FormattedTime value={end} />
    </span>
  );
}

function differentDayTimespan(start: Date, end: Date): React.ReactElement<{}> {
  return (
    <span>
      <span className="timespan--date">
        <FormattedDate
          value={start}
          weekday="short"
          month="short"
          day="numeric"
        />{' '}
        <FormattedTime value={start} />
      </span>
      <span> - </span>
      <span className="timespan--date">
        <FormattedDate
          value={end}
          weekday="short"
          month="short"
          day="numeric"
        />{' '}
        <FormattedTime value={end} />
      </span>
    </span>
  );
}

function isSameDay(date1: Date, date2: Date): boolean {
  return (
    date1.getDate() === date2.getDate() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getFullYear() === date2.getFullYear()
  );
}
