import { createContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { useSelector } from "react-redux";
import { HubConnectionBuilder } from "@microsoft/signalr";

export const UserContext = createContext();

export const UserProvider = (props) => {
  const [user, setUser] = useState(null);
  const navigate = useNavigate();
  
  const status = useSelector((s) => s.status);

  window.addEventListener("beforeunload", () => {
    // that means the user probably shut the browser down without loging out
    if (localStorage.getItem("activeOnes")) {
      disconnect();
    }
  });

  if (JSON.parse(localStorage.getItem('user'))) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${JSON.parse(localStorage.getItem('user')).token}`;
  }

  useEffect(() => {
    if (localStorage.getItem("user") !== undefined) {
      setUser(JSON.parse(localStorage.getItem("user")));
    }
  }, []);

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

    const fulfilled = () => {
      connection
        .send("Unsubscribe", {
          id: user.id,
          connId: status.connection.connectionId,
        })
        .then(() => console.log("bye"));
    };

    const rejected = () => {
      console.log("nope");
    };

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

  const logOut = () => {
    localStorage.removeItem("user");
    localStorage.removeItem("activeOnes");
    disconnect();
    setUser(null);
    navigate("/login");
  };

  return (
    <UserContext.Provider value={{ user, setUser, logOut }}>
      {props.children}
    </UserContext.Provider>
  );
};
