import styled from "@emotion/styled";
import React from "react";
import { useQuery } from "react-apollo";
import { useParams, withRouter } from "react-router-dom";
import { CurrentUser_me, GetSlideshowState } from "../graphql/generated/types";
import { GET_SLIDESHOW_STATE } from "../graphql/queries";
import withPlatform, { PlatformProps } from "../platform/withPlatform";
import SlideshowContainer from "./SlideshowContainer";

type Props = {
  user: CurrentUser_me;
} & PlatformProps;

function SlideshowPage(props: Props) {
  const { id } = useParams() as any;

  const { data, loading } = useQuery<GetSlideshowState>(GET_SLIDESHOW_STATE, {
    variables: { id },
    fetchPolicy: "network-only",
  });

  if (loading || !data) {
    return <div>Loading</div>;
  }

  const initialSlideshowState = data.getSlideshowState
    ? {
        subscribers: JSON.parse(data.getSlideshowState.subscribers),
        mouseInfo: JSON.parse(data.getSlideshowState.mouseInfo),
        slides: JSON.parse(data.getSlideshowState.slides),
        subscriberSelectedElements: JSON.parse(
          data.getSlideshowState.subscriberSelectedElements
        ),
      }
    : {
        subscribers: {},
        mouseInfo: {},
        slides: {},
        subscriberSelectedElements: {},
      };

  return (
    <SlideshowContainer
      user={props.user}
      slideshowId={id}
      slideshowState={initialSlideshowState}
    />
  );
}

export default withPlatform(withRouter(SlideshowPage as any));

const Container = styled.div``;
