import React, { useState } from "react";
import { useQuery } from "react-apollo";
import ScheduleCalendarComponent from "./schedule-calendar.component";
import { QUERY_ALL_ACTIVE_APPOINTMENTS } from "../../graphql/appointments.queries";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import AlertComponent from "../alert/alert.component";

export default function ScheduleCalendarContainer() {
  const { loading, error, data, refetch } = useQuery(
    QUERY_ALL_ACTIVE_APPOINTMENTS,
    {
      fetchPolicy: "network-only"
    }
  );
  const scheduleModalState = useState(false);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent message={error.message} type="error" />;
  let normalizedData = data.appointments.map(e => {
    //Required becuase Hasura returns a string instead of a date object.
    return Object.assign(
      {},
      e,
      { start: new Date(e.start) },
      { end: new Date(e.end) }
    );
  });

  return (
    <ScheduleCalendarComponent
      scheduleModalState={scheduleModalState}
      refetch={refetch}
      data={data ? normalizedData : null}
    />
  );
}
