function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { unByKey } from "ol/Observable";
import { useSelector } from "react-redux";
import PropTypes from "prop-types";
import { makeStyles } from "@mui/styles";
import { Divider } from "@mui/material";
import MenuItem from "../../../components/Menu/MenuItem";
import usePrevious from "../../../utils/usePrevious";
import DvLineInfo from "../DvLineInfo";
import DvLineTitle from "../DvLineTitle";
import removeDuplicates, { getId } from "../../../utils/removeDuplicateFeatures";
import parseDvFeatures from "../dvParseFeatures";
import { DV_DAY_NIGHT_REGEX, DV_KEY } from "../../../utils/constants";
import useHasScreenSize from "../../../utils/useHasScreenSize";
import useDisableIosElasticScrollEffect from "../../../utils/useDisableIosElasticScrollEffect";
const useStyles = makeStyles(theme => {
  return {
    root: {
      "&.wkp-menu-item": {
        marginTop: "0 !important",
        border: "none !important"
      },
      "& .wkp-menu-item-header": {
        height: "40px !important",
        "&.open": {
          borderBottom: "none !important"
        }
      },
      "& .wkp-menu-item-header-toggler": {
        marginRight: 5
      }
    },
    teaser: {
      maxHeight: props => props.isMobile ? 200 : 400,
      position: "relative",
      overflow: "hidden",
      pointerEvents: "none",
      "&::after": _objectSpread(_objectSpread({}, theme.styles.bottomFade["&::after"]), {}, {
        bottom: 0,
        left: 0,
        pointerEvents: "none",
        width: "100%",
        height: "10em"
      }),
      "& .open": {
        "& .wkp-menu-item-header-toggler": {
          transform: "rotate(180deg)"
        }
      }
    },
    featureInfos: {
      maxHeight: "100%",
      overflow: "auto"
    },
    featureInfoItem: {
      marginLeft: 38,
      marginRight: 16
    },
    imageLine: {
      "& img": {
        width: "100%"
      }
    },
    spacer: {
      height: 100
    }
  };
});
function DvFeatureInfo(_ref) {
  let {
    filterByType = false
  } = _ref;
  const featureInfo = useSelector(state => state.app.featureInfo);
  const layers = useSelector(state => state.map.layers);
  const embedded = useSelector(state => state.app.embedded);
  const [infoKey, setInfoKey] = useState();
  const isMobile = useHasScreenSize();
  const [teaser, setTeaser] = useState(true);
  const [expandedHeight, setExpandedHeight] = useState();
  const classes = useStyles({
    isMobile
  });
  const teaserOnClick = useCallback(() => {
    return teaser ? setTeaser(false) : undefined;
  }, [teaser]);
  const [revision, forceRender] = useState();
  const [overflowNode, setOverflowNode] = useState();
  useDisableIosElasticScrollEffect(embedded && overflowNode);
  const dvMainLayer = useMemo(() => layers.find(l => l.key === "".concat(DV_KEY, ".main")), [layers]);
  const layersVisible = useMemo(() => layers.filter(l => DV_DAY_NIGHT_REGEX.test(l.key) && l.visible).map(l => l.key),
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [layers, revision]);
  const dvFeatures = useMemo(() => {
    let features = [];
    const dvInfo = featureInfo.find(i => i.layer === dvMainLayer);
    if (dvInfo && dvInfo.features.length !== 0) {
      // When we click on a station/label we select the lines using the direktverbundung_ids
      if (dvMainLayer.highlightedStation) {
        const dvIds = JSON.parse(dvMainLayer.highlightedStation.get("direktverbindung_ids") || "[]");
        features = dvIds.map(id => {
          return dvMainLayer.allFeatures.find(f => !!f.get("mapboxFeature") && getId(f) === id);
        });
      } else {
        features = dvInfo.features.filter(feat => {
          var _feat$get;
          return !feat.get("mapboxFeature") || (feat === null || feat === void 0 || (_feat$get = feat.get("mapboxFeature")) === null || _feat$get === void 0 ? void 0 : _feat$get.sourceLayer) === "ch.sbb.direktverbindungen_trips";
        });
      }
    }
    features.sort(feat => feat.get("line") === "night" ? -1 : 1);
    const cleaned = removeDuplicates(parseDvFeatures(features));
    return filterByType ? cleaned.filter(feat => !!layersVisible.find(layerKey => {
      return "".concat(DV_KEY, ".").concat(feat.get("line")) === layerKey;
    })) : cleaned;
  }, [featureInfo, filterByType, layersVisible, dvMainLayer]);
  const previousFeatureInfo = usePrevious(featureInfo);
  const previousDvFeatures = usePrevious(dvFeatures);
  const previousInfoKey = usePrevious(infoKey);
  useEffect(() => {
    if (featureInfo !== previousFeatureInfo) {
      setTeaser(true);
      setInfoKey(getId(dvFeatures[0]));
      return;
    }
    if (dvFeatures !== previousDvFeatures) {
      const previousSelectedFeature = dvFeatures.find(feat => getId(feat) === previousInfoKey);
      if (previousInfoKey) {
        setInfoKey(getId(previousSelectedFeature) || getId(dvFeatures[0]));
      }
    }
  }, [dvFeatures, previousDvFeatures, previousInfoKey, featureInfo, previousFeatureInfo]);
  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", evt => {
        forceRender(revision + 1);
        const {
          target: targetLayer
        } = evt;
        if (DV_DAY_NIGHT_REGEX.test(targetLayer.key)) {
          setInfoKey(null);
        }
      });
    })) || [];
    // Force render after first render because visibility of layers is  not yet applied.
    if (revision === undefined) {
      forceRender(0);
    }
    return () => {
      unByKey(olKeys);
    };
  }, [layers, revision]);
  useEffect(() => {
    if (dvFeatures.length > 0 && infoKey) {
      const selectedFeature = dvFeatures.find(feat => getId(feat) === infoKey);
      dvMainLayer.selectLine(selectedFeature ? [selectedFeature] : []);
    }
    return () => {
      dvMainLayer.selectLine([]);
    };
  }, [dvFeatures, dvMainLayer, infoKey]);
  if (!(dvFeatures !== null && dvFeatures !== void 0 && dvFeatures.length)) return null;
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(classes.featureInfos),
    ref: node => setOverflowNode(node)
  }, dvFeatures.length > 1 ? dvFeatures.map(feat => {
    const id = getId(feat);
    const title = feat.get("name");
    const isNightTrain = feat.get("line") === "night";
    const active = infoKey === id;
    return (
      /*#__PURE__*/
      // eslint-disable-next-line jsx-a11y/control-has-associated-label
      React.createElement("div", {
        key: id,
        role: "menuitem",
        tabIndex: teaser ? "-1" : null,
        onClick: teaserOnClick,
        onKeyDown: teaserOnClick,
        style: {
          cursor: teaser ? "pointer" : "auto"
        }
      }, /*#__PURE__*/React.createElement(MenuItem, {
        dataId: id,
        onCollapseToggle: open => {
          setTeaser(false);
          if (active && teaser) {
            return;
          }
          setInfoKey(open ? null : id);
          // We select the feature here instead of DvLineInfo
          // to prevent excessive map layer rerenders.
          dvMainLayer.select(open ? [] : [feat]);
          const vias = feat.get("vias");
          if (!vias.find(via => {
            var _dvMainLayer$highligh;
            return via.uid === ((_dvMainLayer$highligh = dvMainLayer.highlightedStation) === null || _dvMainLayer$highligh === void 0 ? void 0 : _dvMainLayer$highligh.get("uid"));
          })) {
            dvMainLayer.highlightStation();
          }
        },
        className: "wkp-dv-feature-info ".concat(classes.root).concat(active && teaser ? " ".concat(classes.teaser) : ""),
        collapsed: !active,
        open: active,
        title: /*#__PURE__*/React.createElement(DvLineTitle, {
          layer: dvMainLayer,
          feature: feat,
          title: title,
          active: active,
          isNightTrain: isNightTrain,
          teaser: active && teaser
        }),
        menuHeight: expandedHeight
      }, /*#__PURE__*/React.createElement("div", {
        className: classes.featureInfoItem,
        ref: active ? el => setExpandedHeight(el !== null && el !== void 0 && el.clientHeight ? el.clientHeight + 10 : undefined) : null
      }, /*#__PURE__*/React.createElement(DvLineInfo, {
        feature: active ? feat : null,
        layer: dvMainLayer
      }))), /*#__PURE__*/React.createElement(Divider, null))
    );
  }) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    style: {
      padding: 10
    }
  }, /*#__PURE__*/React.createElement(DvLineTitle, {
    title: dvFeatures[0].get("name"),
    active: true,
    isNightTrain: dvFeatures[0].get("line") === "night",
    layer: dvMainLayer,
    feature: dvFeatures[0]
  })), /*#__PURE__*/React.createElement("div", {
    className: classes.featureInfoItem
  }, /*#__PURE__*/React.createElement(DvLineInfo, {
    feature: dvFeatures[0],
    layer: dvMainLayer
  }))), !isMobile && dvFeatures.length ? /*#__PURE__*/React.createElement("div", {
    className: classes.spacer
  }) : null);
}
DvFeatureInfo.propTypes = {
  filterByType: PropTypes.bool
};
export default DvFeatureInfo;
//# sourceMappingURL=DvFeatureInfo.js.map