import React from 'react';
import styles from './FloorControl.styl';

export default class DeleteArea extends React.Component {

  constructor(props) {
    super(props);
    this.onMouseMove = this.onMouseMove.bind(this);
    this.onTouchMove = this.onTouchMove.bind(this);
    this.onDragMove = this.onDragMove.bind(this);
    this.setRef = this.setRef.bind(this);
    this.inRange = this.inRange.bind(this);
  }

  componentDidMount() {
    // Usually we are interested in coordinates relative to the floorplan viewport,
    // but in this case we want them relative to the browser viewport.
    // Because of this we don't rely on the default 'trackCursor' function here.
    document.addEventListener('mousemove', this.onMouseMove, true);
    document.addEventListener('touchmove', this.onTouchMove, true);
  }

  componentWillUnmount() {
    document.removeEventListener('mousemove', this.onMouseMove, true);
    document.removeEventListener('touchmove', this.onTouchMove, true);
  }

  onMouseMove(e) {
    const cursorPosition = {
      x: e.clientX,
      y: e.clientY
    };
    this.onDragMove(cursorPosition);
  }

  onTouchMove(e) {
    if (e.touches.length !== 1) return;
    const cursorPosition = {
      x: e.touches[0].clientX,
      y: e.touches[0].clientY
    };
    this.onDragMove(cursorPosition);
  }

  onDragMove(cursorPosition) {
    const { markForDeletion } = this.props;
    if (this.inRange(cursorPosition) && markForDeletion) markForDeletion();
  }

  setRef(element) {
    this.element = element;
  }

  inRange(cursorPosition) {
    if (!this.element) return false;
    const { y } = cursorPosition;
    const { top, height } = this.element.getBoundingClientRect();
    return y >= top && y < (top + height);
  }

  render() {
    return (
      <div
        ref={this.setRef}
        className={styles.floorControlDelete}
      />
    );
  }

}
