import {useQuery} from "@tanstack/react-query";
import {exportPoints} from "../../../api";
import {handleExportSuccess} from "../ExportButton";
import {appendFiltersInUse} from "../../../utils.js";
import {useDzkhFilters} from "../../../stores/useDzkhFilters.js";
import { useWeatherFilter } from "../../../dzkh-features/WeatherSlider/useWeatherFilter.js";
import { useSimulateAccident } from "../../../stores/useSimulateAccident.js";
import { tempMapper } from "../../../config.js";
import { useUpdateLayerCounter } from "../../../stores/useUpdateLayerCounter.js";

export const useExportData = (enabled, onSettled) => {
  const { filters, consumer_filter, source_filter, consumer_type, wall_material, energy_class } = useDzkhFilters();
  const { value } = useWeatherFilter();
  const { selectedSourceConfig } = useSimulateAccident()
  const t = tempMapper[value];
  const {
    region,
  } = filters;

  const getParams = () => {
    const params = new URLSearchParams();

    const customFilters = [];
    if (consumer_filter && source_filter) {
      const cK = consumer_filter.key + "_" + t;
      const sK = source_filter.key + "_" + t;
      const cFilter = `${cK}__gte=${consumer_filter.gt}&${cK}__lte=${consumer_filter.lt}`;
      const sFilter = `${sK}__gte=${source_filter.gt}&${sK}__lt=${source_filter.lt}`;
      customFilters.push(`(${sFilter})|(${cFilter})`);
    }

    if (selectedSourceConfig) {
      if (selectedSourceConfig.sourceId) customFilters.push(`(tp_number=${selectedSourceConfig.sourceId})`);
      if (selectedSourceConfig.dispatcherNumber) customFilters.push(`(ods_number=${selectedSourceConfig.dispatcherNumber})`);
    }

    if (customFilters.length !== 0) {
      params.append("filters", customFilters.join("&"));
    }

    if (consumer_filter && !source_filter) {
      params.append(consumer_filter.key + "_" + t + "__gt" , consumer_filter.gt)
      params.append(consumer_filter.key + "_" + t + "__lt", consumer_filter.lt)
    }
    if (source_filter && !consumer_filter) {
      params.append(source_filter.key + "_" + t + "__gt" , source_filter.gt)
      params.append(source_filter.key + "_" + t + "__lt", source_filter.lt)
    }

    return params;
  }

  return useQuery(
    ["export-initial", filters],
    async () => {

      return await exportPoints(getParams(), region);
    },
    {
      enabled,
      onSuccess: handleExportSuccess,
      onSettled,
      retry: false,
    }
  );
};
