import * as signalR from "@microsoft/signalr";
import { clearCacheKey, getCachedData } from "../slices/apiDataManager";
import showToast from "./toastService";
import eventBus from "./eventBus";
import { useSelector } from "react-redux";
import { clearApiCacheKey } from "../slices/apiCacheSlice";
const base_Url = process.env.VITE_BASE_URL;
// const base_Url = "https://devapi.marcoaiot.com";
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) => {
    // console.log("Notification received:", data);
    if (data.keyword == "Attendance") {
      const checkIn = data.response.checkInTime.substring(0, 10);
      if (data.loginUserId != loggedUser?.employeeInfo.id) {
        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 (data.keyword == "Create_Project" || data.keyword == "Update_Project") {
      clearCacheKey("projectslist");
      eventBus.emit("project", data);
    }
  });

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

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