import {useQuery} from "@tanstack/react-query";
import {api} from "../../api.js";
import { useWeatherFilter } from "../WeatherSlider/useWeatherFilter.js";

export const useGetDzkhFiltersRange = (field) => {
  return useQuery(
    ["dzkh-filter-range", field],
    async () => {
      const { data, isInitialLoading, isFetching } = await api.get(
        `/api/data/filters_ranges/?field=${field}`
      );
      return {data, isLoading: isInitialLoading || isFetching};
    },
    {
      select: ({data, isLoading}) => {
        let r;
        if (!data || !data[field]) r = [0, 0];
        else r = [data[field].min, data[field].max];
        return {
          range: r,
          isLoading: isLoading
        };
      },
    }
  );
};

export const useGetDzkhFiltersValues = (field) => {
  return useQuery(
    ["dzkh-filter-values", field],
    async () => {
      const { data, isInitialLoading, isFetching } = await api.get(
        `/api/data/filters_ranges/?field=${field}`
      );
      return {data, isLoading: isInitialLoading || isFetching};
    },
    {
      select: ({data, isLoading}) => {
        if (!data) return [];
        return [...data[field]];
      },
    }
  );
};

export const useShap = (id) => {
  return useQuery(
    ["dzkh-shap", id],
    async () => {
      const { data, isInitialLoading, isFetching } = await api.get(
        `/api/data/${id}/data_shap/`
      );
      return {data, isLoading: isInitialLoading || isFetching};

    },
    {
      select: (raw) => {
        return raw.data.shap
      }
    }
  );
};

export const useCrushSummary = (id) => {
  const {value: temp} = useWeatherFilter();
  if (!id) return {data: null};
  return useQuery(
    ["dzkh-crush", id],
    async () => {
      const { data, isInitialLoading, isFetching } = await api.get(
        `/api/data/${id}/crush_summary/?current_temp=${temp}`
      );
      return {data, isLoading: isInitialLoading || isFetching};

    },
    {
      select: (raw) => {
        return raw.data
      }
    }
  );
};
