import React from "react";
import { connect } from "redux-bundler-react";
import {
  BasicToolbarButton,
  BasicToolbarMenuUp,
  BasicToolbarMenuItem,
} from "../../application-controls";
import { transform } from "ol/proj";
import Settings from "./coordinate-display-settings";

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

    //Parent container for coord copy.
    const container = document.createElement("div");
    container.id = "cm-copy-coords";
    document.body.appendChild(container);

    this.state = {
      copyActive: false,
      defaultZoom: 13,
      newx: "",
      newy: "",
      x: "0.0000",
      y: "0.0000",
      copyContainer: container,
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
    this.updateNewCoord = this.updateNewCoord.bind(this);
    this.zoomToLocation = this.zoomToLocation.bind(this);
    this.toggleCopy = this.toggleCopy.bind(this);
    this.startCopy = this.startCopy.bind(this);
    this.stopCopy = this.stopCopy.bind(this);
    this.copyCoords = this.copyCoords.bind(this);
    this.throttledPointerMove = this.throttledPointerMove.bind(this);
    this.pointerMove = this.pointerMove.bind(this);
    this.openSettings = this.openSettings.bind(this);
  }

  toggleCopy() {
    this.setState({ copyActive: !this.state.copyActive }, () => {
      if (this.state.copyActive) {
        this.startCopy();
      } else {
        this.stopCopy();
      }
    });
  }

  startCopy() {
    const { map, doSetCursor, doNotificationsFire } = this.props;
    doSetCursor("crosshair");
    map.on("pointermove", this.throttledPointerMove, this);
    map.on("singleclick", this.copyCoords, this);
    doNotificationsFire({
      message: "Click on map to copy coordinates.",
      level: "info",
    });
  }

  stopCopy() {
    const { map, doSetCursor } = this.props;
    doSetCursor();
    map.un("pointermove", this.throttledPointerMove, this);
    map.un("singleclick", this.copyCoords, this);
  }

  copyCoords(e) {
    const { doNotificationsFire } = this.props;
    const { copyContainer } = this.state;
    const { x, y } = this.state;

    //Add temp child node.
    const valueEl = document.createElement("input");
    copyContainer.appendChild(valueEl);
    valueEl.value = x + ", " + y;
    valueEl.select();
    document.execCommand("copy");

    //Remove node
    copyContainer.removeChild(copyContainer.childNodes[0]);

    doNotificationsFire({
      title: "Coordinate Display",
      message: "Copied " + x + ", " + y + " to the clipboard",
      level: "info",
    });
    this.setState({ copyContainer: copyContainer });
    this.toggleCopy();
  }

  throttledPointerMove(e) {
    if (!this.timeout) {
      this.timeout = window.setTimeout(() => {
        this.timeout = null;
        this.pointerMove(e);
      }, 100);
    }
  }

  pointerMove(e) {
    const { displayProjection } = this.props;
    const coord = e.coordinate;
    const projected = transform(coord, "EPSG:3857", displayProjection);
    this.setState({
      x: "" + Math.round(projected[0] * 10000) / 10000,
      y: "" + Math.round(projected[1] * 10000) / 10000,
    });
  }

  handleKeyUp(e) {
    if (e.keyCode === 13) {
      this.zoomToLocation();
    }
  }

  updateNewCoord(e) {
    const key = "new" + e.currentTarget.dataset.coord;
    const val = e.currentTarget.value;
    this.setState({ [key]: val });
  }

  zoomToLocation() {
    const { displayProjection, doZoomToLocation } = this.props;
    const { newx, newy, defaultZoom } = this.state;
    if (newx && newy) {
      const center = transform(
        [Number(newx), Number(newy)],
        displayProjection,
        "EPSG:3857"
      );
      doZoomToLocation(center, defaultZoom);
    }
  }

  openSettings() {
    const { doModalOpen } = this.props;
    doModalOpen({
      children: [Settings],
      options: {},
      openedBy: "PositionText",
    });
  }

  render() {
    const { displayProjection } = this.props;
    const { newx, newy } = this.state;
    return (
      <BasicToolbarButton
        enabled={true}
        dropup={true}
        iconClass=""
        title={`Current Code ${displayProjection}`}
        text={displayProjection}
        onDeactivate={this.cleanUp}
      >
        <BasicToolbarMenuUp>
          <BasicToolbarMenuItem
            active={false}
            iconClass="mdi mdi-content-copy icon-inline"
            title="Copy Coordinate to Clipboard"
            text="Copy Coordinate to Clipboard"
            onClick={this.toggleCopy}
            passProps={{}}
          />
          <BasicToolbarMenuItem
            active={false}
            iconClass="mdi mdi-map-marker-radius icon-inline"
            title="Go to Coordinate"
            text="Go to Coordinate"
            onClick={this.zoomToLocation}
            passProps={{}}
          />
          <li>
            <span className="cm-form-horizontal">
              <div className="cm-form-group" style={{ marginBottom: 0 }}>
                <label className="col-md-1" style={{ paddingTop: "3px" }}>
                  X
                </label>
                <div className="col-md-10">
                  <input
                    type="text"
                    className="cm-form-control cm-input-sm"
                    onKeyUp={this.handleKeyUp}
                    onChange={this.updateNewCoord}
                    value={newx}
                    data-coord="x"
                    placeholder="Enter Longitude.."
                  />
                </div>
              </div>
            </span>
          </li>
          <li>
            <span className="cm-form-horizontal">
              <div className="cm-form-group" style={{ marginBottom: 0 }}>
                <label className="col-md-1" style={{ paddingTop: "3px" }}>
                  Y
                </label>
                <div className="col-md-10">
                  <input
                    type="text"
                    className="cm-form-control cm-input-sm"
                    onKeyUp={this.handleKeyUp}
                    onChange={this.updateNewCoord}
                    value={newy}
                    data-coord="y"
                    placeholder="Enter Latitude.."
                  />
                </div>
              </div>
            </span>
          </li>
          <BasicToolbarMenuItem
            active={false}
            iconClass="mdi mdi-settings icon-inline"
            title="Set Display Coordinate System"
            text="Set Display Coordinate System"
            onClick={this.openSettings}
            passProps={{}}
          />
        </BasicToolbarMenuUp>
      </BasicToolbarButton>
    );
  }
}

export default connect(
  "selectMap",
  "selectDisplayProjection",
  "doSetCursor",
  "doZoomToLocation",
  "doNotificationsFire",
  "doModalOpen",
  CoordinateInteraction
);
