import * as signalR from "@microsoft/signalr";
import {
  cacheData,
  clearCacheKey,
  getCachedData,
} from "../slices/apiDataManager";
import showToast from "./toastService";
import eventBus from "./eventBus";
import { useSelector } from "react-redux";
import { clearApiCacheKey } from "../slices/apiCacheSlice";
import { BASE_URL } from "../utils/constants";
const base_Url = BASE_URL;
let connection = null;

const targetPath = "";

export function startSignalR(loggedUser) {
  var jwtToken = localStorage.getItem("jwtToken");
  connection = new signalR.HubConnectionBuilder()
    .withUrl(`${base_Url}/hubs/marco`, {
      accessTokenFactory: () => jwtToken,
      transport: signalR.HttpTransportType.LongPolling,
      withCredentials: false,
    })
    .withAutomaticReconnect()
    .build();
  const todayDate = new Date();
  const today = new Date(
    Date.UTC(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate())
  )
    .toISOString()
    .split("T")[0];
  connection.on("NotificationEventHandler", (data) => {
    if (data.loggedInUserId != loggedUser?.employeeInfo.id) {
      // console.log("Notification received:", data);
      // if action taken on attendance module
      if (data.keyword == "Attendance") {
        const checkIn = data.response.checkInTime.substring(0, 10);
        if (today === checkIn) {
          eventBus.emit("attendance", data);
        }
        var onlyDate = Number(checkIn.substring(8, 10));

        var afterTwoDay =
          checkIn.substring(0, 8) + (onlyDate + 2).toString().padStart(2, "0");
        if (
          afterTwoDay <= today &&
          (data.response.activity == 4 || data.response.activity == 5)
        ) {
          eventBus.emit("regularization", data);
        }
        eventBus.emit("attendance_log", data);
      }

      // if create or update project
      if (
        data.keyword == "Create_Project" ||
        data.keyword == "Update_Project"
      ) {
        clearCacheKey("projectslist");
        eventBus.emit("project", data);
      }

      // if assign or deassign employee to any project
      if (data.keyword == "Assign_Project") {
        if (
          data.employeeList.some((item) => item === loggedUser?.employeeInfo.id)
        ) {
          try {
            cacheData("hasReceived", false);
            eventBus.emit("assign_project_one", data);
          } catch (e) {
            console.error("Error in cacheData:", e);
          }
        }
        eventBus.emit("assign_project_all", data);
      }
      // if created or updated infra
      if (data.keyword == "Infra") {
        clearCacheKey("projectInfo");
        eventBus.emit("infra", data);
      }

      // if created or updated Employee
      if (data.keyword == "Employee") {
        clearCacheKey("employeeListByProject");
        clearCacheKey("allEmployeeList");
        clearCacheKey("allInactiveEmployeeList");
        clearCacheKey("employeeProfile");
        clearCacheKey("Attendance");
        clearCacheKey("regularizedList")
        clearCacheKey("AttendanceLogs")
        eventBus.emit("employee", data);
      }
    }
  });

  connection
    .start()
    .then(() => console.log("SignalR connected"))
    .catch((err) => console.error("SignalR error:", err));
}

export function stopSignalR() {
  if (connection) connection.stop();
}
