import React from "react";
import ReleaseNotesList from "./ReleaseNotesList";
import TimelineComponent from "../timeline/TimelineComponent";
import { endpoints } from "../../../utils/api";
import { useSWR, fetcher } from "units/swr";
import { blip } from "utils";
import { dtos } from "types";

const sort = (releases: dtos.ReleaseNote[]) =>
  releases.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

type Props = {
  view: string;
};

const ReleaseNotesContainer: React.FC<Props> = ({ view }) => {
  const { data, isLoading } = useSWR<dtos.ReleaseNote[], Error>(endpoints.system.releaseNotes, fetcher, {
    revalidateOnFocus: false,
    onError: err => blip.error(err.message)
  });

  if (isLoading || !data) return null;

  return (
    <>
      {view === "timeline" ? <TimelineComponent releases={sort(data)} /> : <ReleaseNotesList releases={sort(data)} />}
    </>
  );
};

export default ReleaseNotesContainer;
