import {RANGE_FILTERS_KEYS} from "./stores/usePendingPointsFilters.js";

export function download(filename, data) {
  const downloadLink = window.document.createElement("a");
  downloadLink.href = window.URL.createObjectURL(
    new Blob([data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })
  );
  downloadLink.download = filename;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
}

var chars = {"Ё":"YO","Й":"I","Ц":"TS","У":"U","К":"K","Е":"E","Н":"N","Г":"G","Ш":"SH","Щ":"SCH","З":"Z","Х":"H","Ъ":"'","ё":"yo","й":"i","ц":"ts","у":"u","к":"k","е":"e","н":"n","г":"g","ш":"sh","щ":"sch","з":"z","х":"h","ъ":"'","Ф":"F","Ы":"I","В":"V","А":"A","П":"P","Р":"R","О":"O","Л":"L","Д":"D","Ж":"ZH","Э":"E","ф":"f","ы":"i","в":"v","а":"a","п":"p","р":"r","о":"o","л":"l","д":"d","ж":"zh","э":"e","Я":"Ya","Ч":"CH","С":"S","М":"M","И":"I","Т":"T","Ь":"'","Б":"B","Ю":"YU","я":"ya","ч":"ch","с":"s","м":"m","и":"i","т":"t","ь":"'","б":"b","ю":"yu"," ":""};

export function transliterate(word){
  return word.split('').map(function (char) {
    if (char === " ") return '';
    return chars[char] || char;
  }).join("");
}

export function getFilteredGroups(categories) {
  if (!categories) return [];
  return categories
    .filter((category) => category.visible)
    .map((category) => {
      return {
        ...category,
        groups: [...category.groups.filter((group) => group.visible)],
      }
    })
}

export function fieldHasChanged(filters, ranges, filterKey) {
  const r = ranges[filterKey]
  const gtValue = filters[`${filterKey}__gt`];
  const gtInitial = r ? r[0] : 0 ;
  const ltValue = filters[`${filterKey}__lt`];
  const ltInitial =r ? r[1] : 0;

  const result = !(gtValue === gtInitial && ltValue === ltInitial)

  return {
    result,
    gtValue,
    ltValue,
  }
}

export const doesMatchFilter = (filters, ranges, feature) => {
  const { prediction, categories, region } = filters;
  const {
    prediction_current,
    category,
    area,
    district,
    area_id,
    district_id,
  } = feature.properties;

  const doesMatchPredictionFilter =
    prediction_current >= prediction[0] &&
    prediction_current <= prediction[1];

  const doesMatchCategoriesFilter =
    categories.length > 0 ? categories.includes(category) : true;

  const doesMatchOtherFilters = () => {
    let res = true;
    RANGE_FILTERS_KEYS.map((filterKey) => {
      if (fieldHasChanged(filters, ranges, filterKey).result && res) {
        res =
          feature.properties[filterKey] >= filters[`${filterKey}__gt`] &&
          feature.properties[filterKey] <= filters[`${filterKey}__lt`];
      }

    });

    return res;
  }

  const doesMatchRegionFilter = () => {
    if (!region) return true;

    if (region.type === "ao") {
      return (district ?? district_id) === region.id;
    } else {
      return (area ?? area_id) === region.id;
    }
  };

  return (
    doesMatchPredictionFilter &&
    doesMatchCategoriesFilter &&
    doesMatchRegionFilter() &&
    doesMatchOtherFilters()
  );
};

export const appendFiltersInUse = (params, filters, ranges) => {
  RANGE_FILTERS_KEYS.map((filterKey) => {
    if (!fieldHasChanged(filters, ranges, filterKey).result) return;
    if (/d[0-9]/.test(filterKey)) {
      params.append('dist_to_group__gt', [
        filterKey.split('d')[1],
        filters[`${filterKey}__gt`] - 1
      ].join(','));
      if (filters[`${filterKey}__lt`] < 4000) {
        params.append('dist_to_group__lt', [
          filterKey.split('d')[1],
          filters[`${ filterKey }__lt`] + 1
        ].join(','));
      }
    } else {
      params.append(`${filterKey}__gt`, filters[`${filterKey}__gt`] - 1);
      params.append(`${filterKey}__lt`, filters[`${filterKey}__lt`] + 1);
    }
  });
  if (predictionHasChanged(filters, ranges)) {
    params.append("prediction_current[]", filters.prediction);
  }
}

export const predictionHasChanged = (filters, ranges) => {
  const gtChanged = ranges.prediction[0] !== filters.prediction[0];
  const ltChanged = ranges.prediction[1] !== filters.prediction[1];
  return gtChanged || ltChanged;
}

export const workingFilterHasChanged = (filter, ranges, fieldKey) => {
  if (!ranges[fieldKey]) return false;
  const gtChanged = ranges[fieldKey][0] !== filter[0];
  const ltChanged = ranges[fieldKey][1] !== filter[1];
  return gtChanged || ltChanged;
}


export const isNil = (value) =>
  value === undefined || value === null || value === "";
