import axios from "axios";
import { queryClient } from "@/components/ReactQueryWrapper/ReactQueryWrapper";
import { IGetUserVehicleExForIndexResponse } from "@/queries/records.interfaces";
import { IGEO } from "@/interfaces/alarms";
import { StandardVehicle } from "./StandardVehicle";

export interface IAlarm {
    DevIDNO: string;
    Gps: {
        dct: number;
        gd: number;
        gt: string;
        hx: number;
        lat: number;
        lc: number;
        lid: number;
        lng: number;
        mlat: string;
        mlng: string;
        net: number;
        pk: number;
        s1: number;
        s2: number;
        s3: number;
        s4: number;
        sfg: number;
        snm: number;
        sp: number;
        sst: number;
        t1: number;
        t2: number;
        t3: number;
        t4: number;
        stp: number;
        yl: number;
    };
    desc: string;
    guid: string;
    hd: number;
    img: string;
    info: number;
    p1: number;
    p2: number;
    p3: number;
    p4: number;
    rve: number;
    srcAt: number;
    srcTm: string;
    stType: number;
    time: string;
    type: number;
}

export class StandardAlarm {
    info: IAlarm;
    
    constructor(info: IAlarm) {
       this.info = info
    }

    getVehicle() {
        const indexData = queryClient.getQueryData(['GetUserVehicleExForIndex']) as IGetUserVehicleExForIndexResponse
        const vehData = indexData.vehicles.find((el) => el.dl[0].id === this.info.DevIDNO.toString());

        if(!vehData) {
            return;
        }

        return new StandardVehicle(vehData as any);
    }

    async getLocation(): Promise<IGEO> {
        const data = queryClient.getQueryData(['geocoder', `${this.info.Gps.mlat},${this.info.Gps.mlng}`]) as any

        if(data) {
            return data;
        }

        const res = await axios.get(`${process.env.NEXT_PUBLIC_GEO_HOST}/api/geocoder`, {
            params: {
                location: `${this.info.Gps.mlat},${this.info.Gps.mlng}`,
                lang: 'en',
                toMap: 1
            }
        }).then((res) => res.data.data[0]).then((data) => {
            queryClient.setQueryData(['geocoder', `${this.info.Gps.mlat},${this.info.Gps.mlng}`], data)

            return data;
        })

        return res;
    }
}