import React from "react";
import { connect } from "redux-bundler-react";
import { getLayer } from "../../openlayers-utils/layer-utilities";
import GeoJSON from "ol/format/GeoJSON";
import { Fill, Stroke, Style, Circle as CircleStyle } from "ol/style";
import isHtml from "is-html";

const style = new Style({
  fill: new Fill({
    color: "rgba(84, 240, 240, 0.6)",
  }),
  stroke: new Stroke({
    color: "rgb(84, 240, 240)",
    width: 1,
  }),
  image: new CircleStyle({
    radius: 8,
    stroke: new Stroke({
      color: "rgb(84, 240, 240)",
    }),
    fill: new Fill({
      color: "rgba(84, 240, 240, 0.6)",
    }),
  }),
});

class ResultListItem extends React.Component {
  constructor(props) {
    super(props);

    const geometryType = props.feature.geometry.type;

    this.layer = getLayer({
      serviceType: "LocalVector",
      visible: true,
      geometryType: geometryType,
      style: style,
      zIndex: 1000,
    });

    const features = new GeoJSON().readFeatures(props.feature, {
      dataProjection: "EPSG:4326",
      featureProjection: "EPSG:3857",
    });
    const src = this.layer.getSource();
    src.addFeatures(features);

    this.handleClick = this.handleClick.bind(this);
    this.handleMouseOut = this.handleMouseOut.bind(this);
    this.handleMouseOver = this.handleMouseOver.bind(this);
  }

  componentWillUnmount() {
    const { map } = this.props;
    map.removeLayer(this.layer);
  }

  handleClick() {
    const { doOpenIdentifyDetails, feature } = this.props;
    doOpenIdentifyDetails(feature, this.layer);
  }

  handleMouseOver() {
    const { map } = this.props;
    map.addLayer(this.layer);
  }

  handleMouseOut() {
    const { map } = this.props;
    map.removeLayer(this.layer);
  }

  render() {
    const { feature } = this.props;

    const key = Object.keys(feature.properties)[0] || "No Properties";
    const val = feature.properties[key];
    return (
      <li
        onClick={this.handleClick}
        onMouseOver={this.handleMouseOver}
        onMouseOut={this.handleMouseOut}
        className="cm-list-group-item pointer overflow-ellipsis"
        style={{ margin: "3px", padding: "2px", cursor: "pointer" }}
        title="View More"
      >
        <p>
          <span className="col-sm-2">
            <i className="mdi mdi-plus icon-inline"></i>
          </span>
          <span className="col-sm-4 overflow-sidebar-identify">{key}</span>
          {isHtml(val) ? (<span className="col-sm-6" dangerouslySetInnerHTML={{ __html: val }}></span>) : (<span className="col-sm-6">{val}</span>)}
        </p>
      </li>
    );
  }
}

export default connect("selectMap", "doOpenIdentifyDetails", ResultListItem);
