import "./PlayerStyles.css";
import React, { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router-dom";

import { Sidebar } from "components/pages/Stream/Sidebar/Sidebar";

import { connectSession } from "store/reducers/ActionCreator";
import { useAppDispatch, useAppSelector } from "hooks/redux";
import { sessionSlice } from "store/reducers/sessionSlice";

type link = {
  id: string;
};

export const PlayerComponent: React.FC<any> = ({ closeStream }) => {
  const { id } = useParams<link>();
  const [click, setClick] = useState(false)
  const dispatch = useAppDispatch();
  const { cleanErrors } = sessionSlice.actions;
  const history = useHistory();

  useEffect(() => {
    dispatch(connectSession(id)).then((res: any) => {
      if (res.error) {
        alert(res.payload);
      }
    });
    return () => {
      dispatch(cleanErrors());
    };
  }, []);

  const { url } = useAppSelector((state) => state.sessionReducer);

  const exitPopup = () => {
    setClick(prev => !prev)
  }

  return (
    <>
      <iframe
        onLoad={(e: any) => e.target.focus()} 
        id="player"
        onBlur={(e) => e.target.focus()} /// element loosing focus and keyboard input doesn't work
        src={url}
        className={"player playerOn"}
        security={""}
        allowFullScreen={true}
      ></iframe>

      <Sidebar exitPopup={click} closeStream={closeStream}></Sidebar>
    </>
  );
};
