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

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

import Controls, { ENDED, 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>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" fill="currentColor">
              <path d="M18 3a1 1 0 00-1.196-.98l-10 2A1 1 0 006 5v9.114A4.369 4.369 0 005 14c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V7.82l8-1.6v5.894A4.37 4.37 0 0015 12c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V3z" />
            </svg>{' '}
            Titel spielt</span>
          <Controls
            playerState={playerState}
            onPause={onPause}
            onPlay={onPlay}
            onRestart={onRestart}
          />
        </Fragment>
      )}
    </Fragment>
  );
};

export default Player;
