import { defineStore } from "pinia";
import { onMounted, ref } from "vue";
import dayjs from "dayjs";
import { getAllDevice } from "@/apis/building";

const useAlarmStore = defineStore("alarmData", () => {
  let timer = null;
  const alarmData = ref([]);
  const allDeviceList = ref([]);

  const getFormateDate = (datetime, format_rule = "YYYY-MM-DD HH:mm") => {
    return dayjs(datetime).format(format_rule);
  };
  // get data from baja
  const getAlarmDataFromBaja = () => {
    const alarms = [];
    const sampleDeviceNames = ["AA", "DeviceB", "DeviceC", "DeviceD"];
    const sampleMsgs = [
      "Over temperature",
      "Power failure",
      "Sensor malfunction",
      "Connection lost",
    ];

    for (let i = 0; i < 3; i++) {
      const timestamp = Date.now() - Math.floor(Math.random() * 100000000);

      const device_number = `NTPC_F1_Dust_EM_U9F_NA_AD_AA${Math.floor(Math.random() * 5) + 1}`;

      alarms.push({
        uuid: `uuid-${i+1}`,
        building_tag: "U9F",
        timestamp_date: new Date(timestamp).toLocaleDateString("en-US"),
        timestamp_time: new Date(timestamp).toLocaleTimeString("en-US"),
        alarmClass: `Class ${Math.floor(Math.random() * 3) + 1}`,
        device_number,
        full_name: `AA${Math.floor(Math.random() * 5) + 1}`,
        msg: sampleMsgs[Math.floor(Math.random() * sampleMsgs.length)],
        sourceState: "offnormal",
        normalTime: new Date(timestamp).toLocaleString("en-US"),
        ackState: "Unacked",
        ackedTime:
          Math.random() > 0.5
            ? new Date(timestamp).toLocaleString("en-US")
            : null,
      });
    }

    alarmData.value = alarms;
  };

  const getDevice = async () => {
    const res = await getAllDevice();
    allDeviceList.value = res.data;
  };

  onMounted(() => {
    getDevice();
  });

  return { getAlarmDataFromBaja, alarmData };
});
export default useAlarmStore;
