import "./playerStyles.css";
import { useHistory, useParams } from "react-router-dom";
import React, { useEffect } from "react";
import { Sidebar } from "../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 dispatch = useAppDispatch();
  const { cleanErrors } = sessionSlice.actions;
  const history = useHistory()

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

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

  return (
    <>
      <iframe
        id='player'
        onBlur={(e) => e.target.focus()} /// element loosing focus and keyboard input doesn't work
        title="stream"
        src={url}
        className={"player playerOn"}
        security={""}
      ></iframe>
      <Sidebar closeStream={closeStream}></Sidebar>
    </>
  );
};
