import { Provider } from "mobx-react";
import React, { useEffect } from "react";
import { ID } from "../../shared/types";
import { CurrentUser_me } from "../graphql/generated/types";
import {
  SlideshowState,
  SlideshowStore,
  SocketActions,
} from "../platform/SlideshowStore";
import withPlatform, { PlatformProps } from "../platform/withPlatform";
import Slideshow from "./Slideshow";

type Props = {
  user: CurrentUser_me;
  slideshowId: ID;
  slideshowState: SlideshowState;
} & PlatformProps;

function SlideshowContainer(props: Props) {
  const store = new SlideshowStore(
    props.user.id,
    props.slideshowId,
    props.slideshowState
  );

  const attemptLeaveRoom = () => {
    store.emit(SocketActions.LEAVE_ROOM, {
      userId: props.user.id,
    });
  };
  useEffect(() => {
    store.emit(SocketActions.ENTER_ROOM, {
      userId: props.user.id,
    });
    window.addEventListener("beforeunload", attemptLeaveRoom);

    return () => {
      store.emit(SocketActions.LEAVE_ROOM, {
        userId: props.user.id,
      });
      window.removeEventListener("beforeunload", attemptLeaveRoom);
    };
  });

  return (
    <Provider store={store}>
      <Slideshow user={props.user} store={store} />
    </Provider>
  );
}

export default withPlatform(SlideshowContainer);
