import { useQuery } from '@tanstack/react-query';
import { Moment } from 'moment';

import { $api, $proxyapi } from '@/api/api';
import { IGetRecordsResponse, IGetUserVehicleExForIndexResponse } from './records.interfaces';

export const useGetUserVehicleExForIndex = () => {
  const query = useQuery({
    queryKey: ['GetUserVehicleExForIndex'],
    queryFn: async () => {
      return $proxyapi
        .get(`/StandardLoginAction_getUserVehicleExForIndex.action`)
        .then((res) => res.data) as Promise<IGetUserVehicleExForIndexResponse>;
    },
  });

  return query;
};

interface IPropsGetRecords {
  DevIDNO: number | string;
  date: Moment;
  start: string;
  end: string;
  fileLocation: string;
  fileType: string;
  recType: string;
  radioType: 'devices' | 'company';
}

export const useGetRecords = (params?: IPropsGetRecords) => {
  const query = useQuery({
    queryKey: ['getRecords', JSON.stringify(params)],
    queryFn: async () => {
      const startArr = params?.start?.split(":") || [0,0];
      const startSec = Number(startArr[0])*60*60+Number(startArr[1])*60
      const endArr = params?.end?.split(":") || [23,59];
      const endSec = Number(endArr[0])*60*60+Number(endArr[1])*60+59

      const IDFilter = params?.radioType === 'company' ? `COMPANYID=${params?.DevIDNO}` : `DevIDNO=${params?.DevIDNO}`


      return $api
        .get(
          `${process.env.NEXT_PUBLIC_RECORDS_HOST}/3/5?DownType=2&${IDFilter}&LOC=${params?.fileLocation}&CHN=-1&YEAR=${params?.date.get('year')}&MON=${((params?.date?.get("month")||0)+1).toString().padStart(2, '0')}&DAY=${params?.date?.get('date').toString().padStart(2, '0')}&RECTYPE=${params?.recType}&FILEATTR=${params?.fileType}&BEG=${startSec}&END=${endSec}&ARM1=0&ARM2=0&RES=0&STREAM=-1&STORE=0&jsession`,
        )
        .then((res) => res.data) as Promise<IGetRecordsResponse>;
    },
    enabled: !!params,
    refetchOnMount: false,
    retry: false
  });

  return query;
};
