import React from "react";
import Activity from "./Activity";
import ChatList from "./ChatList";
import Requests from "./Requests/Requests";
import { useContext, useEffect } from "react";
import { HubConnectionBuilder } from "@microsoft/signalr";
import { UserContext } from "../contexts/userContext";
import { useDispatch } from "react-redux";
import { statusActions } from "../store/status-slice";

const MiddleContainer = ({ showTerm }) => {
  const { user } = useContext(UserContext);

  const dispatch = useDispatch();

  function connect() {
    const connection = new HubConnectionBuilder()
      .withUrl("http://localhost:5116/statusHub")
      .withAutomaticReconnect()
      .build();

    dispatch(statusActions.setStatusConn(connection));

    connection.on("Notify", (data) => {
      if (data.m === "subscription") {
        dispatch(statusActions.addToActiveUsers(data.id));
      } else {
        dispatch(statusActions.removeFromActiveUsers(data.id));
      }
    });

    connection.on("ReceiveList", (data) => {
      dispatch(statusActions.setActiveUsers(data));
    });

    const fulfilled = () => {
      connection.send("Subscribe", user && user.id);
    };

    const rejected = () => {};

    connection.start().then(fulfilled, rejected);
  }

  // Maybe don't work
  useEffect(() => {
    connect();
  }, []);

  return (
    <div className="w-25 mh-100-vh px-2 pe-0 bg-main">
      {showTerm === "chats" && <ChatList />}
      {showTerm === "notifications" && <Activity />}
      {showTerm === "requests" && <Requests />}
    </div>
  );
};

export default MiddleContainer;
