import React, { useEffect, useState, useMemo, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import PropTypes from "prop-types";
import { EventConsumer } from "@geops/create-react-web-component";
import BaseLayerSwitcher from "react-spatial/components/BaseLayerSwitcher";
import useTranslation from "../../utils/useTranslation";
import ResizeHandler from "../ResizeHandler";
import { setScreenDimensions } from "../../model/app/actions";
import MainDialog from "../MainDialog";
import Map from "../Map";
import Menu from "../Menu";
import FeatureMenu from "../FeatureMenu";
import TrackerMenu from "../../menus/TrackerMenu";
import ShareMenu from "../../menus/ShareMenu";
import DrawMenu from "../../menus/DrawMenu";
import ExportMenu from "../../menus/ExportMenu";
import Permalink from "../Permalink";
import Header from "../Header";
import Footer from "../Footer";
import MapControls from "../MapControls";
import Popup from "../Popup";
import Search from "../Search";
import TopicTelephoneInfos from "../TopicTelephoneInfos";
import TopicsMenu from "../TopicsMenu";
import Overlay from "../Overlay";
import { ReactComponent as ChevronLeft } from "../../img/chevronLeft.svg";
import { trackEvent } from "../../utils/trackingUtils";
const defaultElements = {
  header: false,
  footer: false,
  menu: false,
  permalink: false,
  popup: false,
  mapControls: false,
  geolocationButton: false,
  baseLayerSwitcher: false,
  shareMenu: false,
  drawMenu: false,
  trackerMenu: false,
  featureMenu: false,
  exportMenu: false,
  search: false,
  overlay: false,
  menuToggler: false
};
const propTypes = {
  /**
   * History object from react-router
   * @private
   */
  history: PropTypes.shape({
    push: PropTypes.func,
    replace: PropTypes.func
  })
};
function TopicElements(_ref) {
  let {
    history = null
  } = _ref;
  const dispatch = useDispatch();
  const {
    t
  } = useTranslation();
  const activeTopic = useSelector(state => state.app.activeTopic);
  const staticFilesUrl = useSelector(state => state.app.staticFilesUrl);
  const loginUrl = useSelector(state => state.app.loginUrl);
  const map = useSelector(state => state.app.map);
  const [tabFocus, setTabFocus] = useState(false);
  const [node, setNode] = useState(null);
  useEffect(() => {
    const unfocusTab = () => setTabFocus(false);
    const focusTab = e => e.which === 9 && setTabFocus(true);
    document.addEventListener("mousedown", unfocusTab);
    document.addEventListener("keydown", focusTab);
    return function cleanup() {
      document.removeEventListener("mousedown", unfocusTab);
      document.removeEventListener("keydown", focusTab);
    };
  });
  const elements = useMemo(() => {
    const disabled = new URL(window.location.href).searchParams.get("disabled");
    const elts = (activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.elements) || defaultElements;
    if (disabled) {
      disabled.split(",").forEach(element => {
        // Backward compatibility
        if (element === "spyLayer") {
          elts.baseLayerSwitcher = false;
        }
        // Backward compatibility
        if (element === "header") {
          elts.search = false;
          elts.telephoneInfos = false;
        }
        elts[element] = false;
      });
    }
    return elts;
  }, [activeTopic]);
  const baseLayers = useMemo(() => {
    return ((activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.layers) || []).filter(layer => layer.get("isBaseLayer"));
  }, [activeTopic]);

  // We define the images for the base layers using staticFilesUrl because they are too big to be encoded in base64.
  // so when using in the web component (see angular example) the app is able to get them.
  // Images are stored in the gitlab project.
  const baseLayerImages = useMemo(() => {
    const imgs = {};
    baseLayers.forEach(layer => {
      imgs[layer.key] = "".concat(staticFilesUrl, "/img/baselayer/").concat(layer.get("previewImage"), ".jpg");
    });
    return imgs;
  }, [baseLayers, staticFilesUrl]);
  const topicClassName = useMemo(() => {
    let classNamee = "";
    if (activeTopic !== null && activeTopic !== void 0 && activeTopic.key) {
      classNamee = activeTopic.key.toLowerCase().replaceAll(".", "-");
    }
    return classNamee;
  }, [activeTopic]);
  const className = useMemo(() => {
    const classNames = ["tm-trafimage-maps", topicClassName];
    if (elements.header) {
      classNames.push("header");
    }
    if (elements.menu) {
      classNames.push("menu");
    }
    if (elements.mapControls) {
      classNames.push("map-controls");
    }
    return classNames.join(" ");
  }, [topicClassName, elements]);
  const barrierFreeClassName = useMemo(() => {
    const classNames = ["tm-barrier-free"];
    if (!tabFocus) {
      classNames.push("tm-no-focus");
    }
    return classNames.join(" ");
  }, [tabFocus]);
  const onResize = useCallback((entries, width, height) => {
    dispatch(setScreenDimensions({
      width,
      height
    }));
  }, [dispatch]);
  if (!activeTopic) {
    return null;
  }
  return /*#__PURE__*/React.createElement("div", {
    className: className
    // Using useRef, it breaks the doc. ref.current is always null.
    ,
    ref: elt => {
      if (node !== elt) {
        setNode(elt);
      }
    }
  }, node && /*#__PURE__*/React.createElement(ResizeHandler, {
    observe: node,
    forceUpdate: elements.header,
    onResize: onResize
  }), /*#__PURE__*/React.createElement("div", {
    className: barrierFreeClassName
  }, /*#__PURE__*/React.createElement(EventConsumer, null, dispatcher => /*#__PURE__*/React.createElement(Map, {
    map: map,
    maxZoom: activeTopic.maxZoom,
    dispatchHtmlEvent: dispatcher
  })), /*#__PURE__*/React.createElement(Permalink, {
    history: history,
    readOnly: !elements.permalink
  }), elements.search && /*#__PURE__*/React.createElement(Search, null), elements.header && /*#__PURE__*/React.createElement(Header, {
    loginUrl: loginUrl
  }), elements.header && /*#__PURE__*/React.createElement(TopicTelephoneInfos, null), elements.popup && /*#__PURE__*/React.createElement(Popup, null), elements.mapControls && /*#__PURE__*/React.createElement(MapControls, {
    menuToggler: elements.menuToggler,
    geolocation: elements.geolocationButton,
    fitExtent: elements.fitExtent,
    floorSwitcher: elements.floorSwitcher
  }, activeTopic.mapControls), elements.baseLayerSwitcher && /*#__PURE__*/React.createElement(BaseLayerSwitcher, {
    layers: baseLayers,
    titles: {
      button: t("Baselayerwechsel"),
      openSwitcher: t("Baselayer-Menu öffnen"),
      closeSwitcher: t("Baselayer-Menu schliessen")
    },
    layerImages: baseLayerImages,
    closeButtonImage: /*#__PURE__*/React.createElement(ChevronLeft, null),
    t: t,
    onLayerButtonClick: (e, layer) => {
      if (layer) {
        trackEvent({
          eventType: "action",
          componentName: "layer switch button",
          label: t(layer.key),
          location: t(activeTopic.name, {
            lng: "de"
          }),
          variant: t(layer.name || layer.key, {
            lng: "de"
          })
        }, activeTopic);
      }
    }
  }), /*#__PURE__*/React.createElement(Menu, null, elements.menu && /*#__PURE__*/React.createElement(TopicsMenu, null, elements.exportMenu && /*#__PURE__*/React.createElement(ExportMenu, null), elements.drawMenu && /*#__PURE__*/React.createElement(DrawMenu, null), elements.shareMenu && /*#__PURE__*/React.createElement(ShareMenu, null)), elements.featureMenu && /*#__PURE__*/React.createElement(FeatureMenu, null), elements.trackerMenu && /*#__PURE__*/React.createElement(TrackerMenu, null), activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.menu), elements.footer && /*#__PURE__*/React.createElement(Footer, null), elements.overlay && /*#__PURE__*/React.createElement(Overlay, {
    elements: elements
  }), activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.customElements, /*#__PURE__*/React.createElement(MainDialog, null)));
}
TopicElements.propTypes = propTypes;
export default /*#__PURE__*/React.memo(TopicElements);
//# sourceMappingURL=TopicElements.js.map