/* eslint-disable no-param-reassign */
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { FormGroup, FormControlLabel } from "@mui/material";
import { unByKey } from "ol/Observable";
import useTranslation from "../../utils/useTranslation";
import SBBSwitch from "../../components/SBBSwitch";
import { STS_KEY } from "../../utils/constants";
import { setFeatureInfo } from "../../model/app/actions";
const stsStyleLayerRegex = new RegExp("^".concat(STS_KEY, ".validity.gttos$"));
function StsValidityLayerSwitcher() {
  const {
    t
  } = useTranslation();
  const dispatch = useDispatch();
  const [revision, forceRender] = useState();
  const layers = useSelector(state => state.map.layers);
  const stsLayers = useMemo(() => {
    return layers === null || layers === void 0 ? void 0 : layers.filter(layer => stsStyleLayerRegex.test(layer.key));
  }, [layers]);
  const layersVisible = stsLayers.filter(l => l.visible).map(l => l.key);

  // Force render when visibility changes
  useEffect(() => {
    const olKeys = (layers === null || layers === void 0 ? void 0 : layers.map(layer => {
      return layer === null || layer === void 0 ? void 0 : layer.on("change:visible", () => {
        forceRender(value => value + 1);
      });
    })) || [];

    // Force render after first render because visibility of layers is  not yet applied.
    if (revision === undefined) {
      forceRender(0);
    }
    return () => {
      unByKey(olKeys);
    };
  }, [layers, revision, stsLayers]);
  const onChange = useCallback(layer => {
    dispatch(setFeatureInfo([]));
    if (layer.visible) {
      layer.visible = false;
      return;
    }
    layer.visible = true;
  }, [dispatch]);
  return /*#__PURE__*/React.createElement(FormGroup, {
    "data-testid": "sts-validity-layerswitcher"
  }, stsLayers.map(layer => {
    return /*#__PURE__*/React.createElement(FormControlLabel, {
      key: layer.key,
      label: layer.visible ? /*#__PURE__*/React.createElement("b", null, t(layer.name)) : t(layer.name),
      checked: layersVisible.includes(layer.key),
      control: /*#__PURE__*/React.createElement(SBBSwitch, {
        key: layer.key,
        value: layer.key,
        onChange: () => onChange(layer)
      })
    });
  }));
}
StsValidityLayerSwitcher.propTypes = {};
export default StsValidityLayerSwitcher;
//# sourceMappingURL=StsValidityLayerSwitcher.js.map