import React, { useEffect, useState, Fragment, useContext } from "react";
import youtubePlayer from "youtube-player";

import AppContext from "../context/app";

import Controls, { ENDED, PLAYING, PAUSED } from "./controls";

let player;

const Player = ({ hidden }) => {
  const [playerState, setPlayerState] = useState(-1);

  const { openSong } = useContext(AppContext);

  const onPause = () => player && player.pauseVideo();
  const onPlay = () => player && player.playVideo();
  const onRestart = () => {
    player && player.seekTo(openSong.startSeconds || 0);
    player && [PAUSED, ENDED].includes(playerState) && player.playVideo();
  };

  useEffect(onRestart, [!hidden]);

  useEffect(() => {
    const setState = ({ data }) => setPlayerState(data);
    player = youtubePlayer("player", {
      height: "390",
      width: "640"
    });
    player.on("stateChange", setState);
    player.loadVideoById({
      videoId: openSong.id,
      startSeconds: openSong.startSeconds,
      endSeconds: openSong.endSeconds
    });

    return () => {
      player = null;
      setPlayerState(null);
    };
  }, []);

  return (
    <Fragment>
      <div className={hidden ? "hidden" : undefined}>
        <div id="player" />
      </div>
      {hidden && playerState === -1 && <span>🎶 Titel laden...</span>}
      {hidden && playerState > -1 && (
        <Fragment>
          <span>🎶 Titel spielt</span>
          <Controls
            playerState={playerState}
            onPause={onPause}
            onPlay={onPlay}
            onRestart={onRestart}
          />
        </Fragment>
      )}
    </Fragment>
  );
};

export default Player;
