import React from "react";
import { connect } from "redux-bundler-react";
import IdentifySidebarList from "./identify-sidebar-list";
import find from "lodash/find";
import classnames from "classnames";

class IdentifySidebar extends React.Component {
  constructor(props) {
    super(props);
    this.renderResults = this.renderResults.bind(this);
  }

  renderResults() {
    const { identifyResults, cmLayerNames, uidMap } = this.props;
    const subLayerNameMatch = /[:](.+)/i;
    const components = [];
    let counter = 0;

    identifyResults.forEach((r) => {
      const id = r.dataset;
      const lyr = find(cmLayerNames, { teamDatasetId: id });
      const lyrName = !lyr ? uidMap[id] : lyr.displayName;

      Object.keys(r.result).forEach((key) => {
        const fc = r.result[key];
        if (fc && fc.features && fc.features.length) {
          const subLayer = subLayerNameMatch.exec(key);
          const subLayerName = subLayer
            ? subLayer[1] !== lyrName
              ? subLayer[0]
              : ""
            : "";
          components.push(
            <IdentifySidebarList
              features={fc.features}
              displayName={`${lyrName}${subLayerName}`}
              key={counter++}
            />
          );
        }
      });
    });

    return components;
  }

  render() {
    const { primaryPanelShowClose, doToggleIdentifyView } = this.props;

    const listClass = classnames({
      "sidebar-list": !primaryPanelShowClose,
      "thin-scrollbar": true,
      "sidebar-list-show-close-btn": primaryPanelShowClose,
    });
    const listTop = primaryPanelShowClose ? 50 : 30;

    return (
      <div>
        <div className={listClass} style={{ top: listTop }}>
          <div className="row">
            <div className="col-xs-12">
              <button
                type="button"
                className="cm-btn cm-btn-xs cm-btn-default pull-right"
                title="TABLE VIEW"
                onClick={() => {
                  doToggleIdentifyView("table");
                }}
              >
                TABLE VIEW
              </button>
            </div>
          </div>
          {this.renderResults()}
        </div>
      </div>
    );
  }
}

export default connect(
  "selectIdentifyResults",
  "selectCmLayerNames",
  "selectUidMap",
  "selectPrimaryPanelShowClose",
  "doToggleIdentifyView",
  IdentifySidebar
);
