import React from "react";
import ScheduleDayViewComponent from "./schedule-day-view.component";
import { useQuery } from "react-apollo";
import { QUERY_APPOINTMENT_BY_DATE } from "../../graphql/appointments.queries";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import moment from "moment";

export default function ScheduleDayViewContainer({ day }) {
  const { loading, error, data } = useQuery(QUERY_APPOINTMENT_BY_DATE, {
    variables: {
      start: moment(day).startOf("day"),
      end: moment(day).endOf("day")
    },
    skip: !day,
    fetchPolicy: "network-only"
  });

  if (loading) return <LoadingSkeleton paragraph={{ rows: 4 }} />;
  if (error) return <div>{error.message}</div>;
  let normalizedData;
  if (data) {
    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 (
    <ScheduleDayViewComponent data={data ? normalizedData : null} day={day} />
  );
}
