import { date } from 'quasar';
import { Boat } from 'src/stores/boat';
import {
  Interval,
  IntervalTemplate,
  TimeTuple,
} from 'src/stores/schedule.types';

export function arrayToTimeTuples(arr: string[]) {
  const timeTuples: TimeTuple[] = [];
  for (let i = 0; i < arr.length; i += 2) {
    timeTuples.push([arr[i], arr[i + 1]]);
  }
  return timeTuples;
}

export function timeTuplesOverlapped(tuples: TimeTuple[]): Interval[] {
  return intervalsOverlapped(
    tuples.map((tuples) => {
      return {
        resource: '',
        start: '01/01/2001 ' + tuples[0],
        end: '01/01/2001 ' + tuples[1],
      };
    })
  ).map((t) => {
    return { ...t, start: t.start.split(' ')[1], end: t.end.split(' ')[1] };
  });
}

export function intervalsOverlapped(
  blocks: Interval[] | Interval[]
): Interval[] {
  return Array.from(
    new Set(
      blocks
        .sort((a, b) => Date.parse(a.start) - Date.parse(b.start))
        .reduce((acc: Interval[], block, i, arr) => {
          if (i > 0 && block.start < arr[i - 1].end)
            acc.push(arr[i - 1], block);
          return acc;
        }, [])
    )
  );
}

export function copyTimeTuples(tuples: TimeTuple[]): TimeTuple[] {
  return tuples.map((t) => Object.assign([], t));
}
export function copyIntervalTemplate(
  template: IntervalTemplate
): IntervalTemplate {
  return {
    ...template,
    timeTuples: copyTimeTuples(template.timeTuples || []),
  };
}

export function buildInterval(
  resource: Boat,
  time: TimeTuple,
  blockDate: string
): Interval {
  /* When the time zone offset is absent, date-only forms are interpreted
     as a UTC time and date-time forms are interpreted as local time. */
  const result = {
    resource: resource.$id,
    start: new Date(blockDate + 'T' + time[0]).toISOString(),
    end: new Date(blockDate + 'T' + time[1]).toISOString(),
  };
  return result;
}

export const isPast = (itemDate: Date | string): boolean => {
  if (!(itemDate instanceof Date)) {
    itemDate = new Date(itemDate);
  }
  const currentDate = new Date();
  return itemDate < currentDate;
};

export function formatDate(inputDate: string | undefined): string {
  if (!inputDate) return '';
  return date.formatDate(new Date(inputDate), 'ddd MMM Do hh:mm A');
}

export function formatTime(inputDate: string | undefined): string {
  if (!inputDate) return '';
  return date.formatDate(new Date(inputDate), 'hh:mm A');
}
