import Cookies from 'js-cookie';
import axios from "axios";

import { useQuery } from "@tanstack/react-query";
import { $proxyapi } from "@/api/api";
import { queryClient } from '@/components/ReactQueryWrapper/ReactQueryWrapper';
import { StandardAlarm } from '@/classes/StandardAlarm';

export const useStatusesEx = () => {
    const query = useQuery({
        queryKey: ['statuses', 'list'],
        queryFn: async () => {
            const prevState = JSON.parse(sessionStorage.getItem('statusEx') || '{}')

            const updlist = await $proxyapi.post(`/StandardPositionAction_statusEx.action?toMap=11&vType=v3`).then((res) => res.data.status) as any[]

            updlist.forEach((el) => {
                const vid = el.id;

                if(prevState[vid]) {
                    prevState[vid] = {...prevState[vid], ...el}
                } else {
                    prevState[vid] = {...el}
                }
            })

            sessionStorage.setItem('statusEx', JSON.stringify(prevState))

            return prevState;
        },
        refetchInterval: 5000
    })

    return query;
}

export const useAlarms = () => {
    const query = useQuery({
        queryKey: ['alarms', 'info'],
        queryFn: async () => {
            const prevState = JSON.parse(sessionStorage.getItem('alarms') || '{}')
            // const prevState = JSON.parse('{}')
            const allVehicles = Object.keys(queryClient.getQueryData(['statuses', 'list']) as any)

            const updlist = await axios.post(`${process.env.NEXT_PUBLIC_ALARMS_HOST}/66/11`, JSON.stringify(
                {
                    "JSESSIONID": Cookies.get('JSESSIONID')!,
                    "ACCOUNT": "admin",
                    "toMap": 11,
                    "DevIDNO": [
                        ...allVehicles,
                      "@@NOTIFY_EVENT@@"
                    ]
                  }
            ), {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
                }
            }).then((res) => res.data.alarmlist) as any[]

            
            updlist.forEach((el) => {
                const id = el.guid;

                if(prevState[id]) {
                    prevState[id] = {...prevState[id], ...el}
                } else {
                    prevState[id] = {...el}
                }
            })

            sessionStorage.setItem('alarms', JSON.stringify(prevState))

            return Object.fromEntries(Object.keys(prevState).map((key) => [key, new StandardAlarm(prevState[key])])) as Record<string, StandardAlarm>;
        },
        refetchInterval: 5000
    })

    return query;
}