import React from "react";
import { connect } from "redux-bundler-react";
import sortBy from "lodash/sortBy";
import LegendItem from "./legend-item";
import LegendItemMultiple from "./legend-item-multiple";
import LoadingIndicator from "../../application-controls/loading-indicator";
import classnames from "classnames";

class LegendPanel extends React.Component {
  constructor(props) {
    super(props);
    this.renderItems = this.renderItems.bind(this);
  }
  renderItems() {
    const { visibleLayers, legendLayers } = this.props;
    const sortedLayers = sortBy(visibleLayers, ["sortOrder"]).reverse();

    return sortedLayers.map((layer) => {
      if (legendLayers.hasOwnProperty(layer.uid)) {
        switch (layer.type) {
          case "ArcGIS":
          case "ArcGISImage":
          case "EsriFeatureService":
          case "WMS":
            return (
              <LegendItemMultiple
                key={layer.uid}
                layer={layer}
                images={legendLayers[layer.uid]}
              />
            );
          case "LocalVector":
          default:
            return (
              <LegendItem
                key={layer.uid}
                layer={layer}
                image={legendLayers[layer.uid][0]}
              />
            );
        }
      }
    });
  }

  render() {
    const { legendLoading, primaryPanelShowClose } = this.props;
    const listClass = classnames({
      "corpsmap-legend": true,
      "cm-list-group": true,
      "sidebar-list": !primaryPanelShowClose,
      "thin-scrollbar": true,
      "sidebar-list-show-close-btn": primaryPanelShowClose,
    });

    if (legendLoading) {
      return (
        <ul className={listClass}>
          <LoadingIndicator />
        </ul>
      );
    } else {
      return <ul className={listClass}>{this.renderItems()}</ul>;
    }
  }
}
export default connect(
  "selectVisibleLayers",
  "selectLegendLayers",
  "selectLegendLoading",
  "selectPrimaryPanelShowClose",
  LegendPanel
);
