import {
  AUTO_REFRESH_INTERVAL,
  EVENT_BANZONE_DATA,
  EVENT_SEARCH_THINGS,
} from "@/constants";
import { querySearchThings } from "@/controller/DeviceController";
import { queryBanzones } from "@/controller/MapController";
import eventBus from "@/utils/eventBus";

const intervals: {
  banzones: ReturnType<typeof setInterval> | null;
  searchThings: ReturnType<typeof setInterval> | null;
} = {
  banzones: null,
  searchThings: null,
};

export function getBanzonesEventBus() {
  if (intervals.banzones) return;
  const getBanzonesData = async () => {
    try {
      // console.log("Banzones: fetching data...");
      const resp = await queryBanzones();
      if (resp && resp.data && resp.data.length > 0) {
        // console.log("Banzones: emitting", resp.data.length);
        eventBus.emit(EVENT_BANZONE_DATA, resp.data);
      } else {
        console.log("Banzones: no data returned");
      }
    } catch (err) {
      console.error("Banzones: fetch error", err);
    }
  };

  getBanzonesData();
  intervals.banzones = setInterval(() => {
    getBanzonesData();
  }, AUTO_REFRESH_INTERVAL * 60);
}

export function searchThingEventBus(body: Model.SearchThingBody) {
  // Clear interval cũ nếu có
  if (intervals.searchThings) {
    clearInterval(intervals.searchThings);
    intervals.searchThings = null;
  }

  const searchThingsData = async () => {
    // console.log("call api with body:", body);

    try {
      const resp = await querySearchThings(body);
      if (resp && resp.data) {
        eventBus.emit(EVENT_SEARCH_THINGS, resp.data);
      } else {
        console.log("SearchThings: no data returned");
      }
    } catch (err) {
      console.error("SearchThings: fetch error", err);
    }
  };

  // Gọi ngay lần đầu
  searchThingsData();

  // Sau đó setup interval để gọi lại mỗi 30s
  intervals.searchThings = setInterval(() => {
    searchThingsData();
  }, AUTO_REFRESH_INTERVAL * 6); // 30 seconds
}

export function stopEvents() {
  Object.keys(intervals).forEach((k) => {
    const key = k as keyof typeof intervals;
    if (intervals[key]) {
      clearInterval(intervals[key] as ReturnType<typeof setInterval>);
      intervals[key] = null;
    }
  });
}

export function startEvents() {
  getBanzonesEventBus();
}
