import React, { PureComponent } from 'react'

import {
  LONG_TOUCH_DURATION,
  MAX_MOVE,
} from '../common'

export interface Props {
  children: any,
  onLongTouch: () => void
}

export default class LongTouch extends PureComponent<Props> {
  private touchTimer: Number | null = null
  private touchX = 0
  private touchY = 0

  public onTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
    const { pageX, pageY } = e.touches[0]
    this.touchX = pageX
    this.touchY = pageY
    this.touchTimer = Date.now()
  }

  public onTouchEnd = (e: React.TouchEvent<HTMLDivElement>) => {
    const touchDuration = Date.now() - (this.touchTimer as number)
    const { pageX, pageY } = e.changedTouches[0]
    const { onLongTouch } = this.props
    const { touchX, touchY } = this
    const isMove =
      pageX - touchX > MAX_MOVE ||
      touchX - pageX > MAX_MOVE ||
      pageY - touchY > MAX_MOVE ||
      touchY - pageY > MAX_MOVE
    if (touchDuration > LONG_TOUCH_DURATION && onLongTouch && !isMove) {
      onLongTouch()
    }
  }

  public render() {
    return (
      <div
        onTouchStart={this.onTouchStart}
        onTouchEnd={this.onTouchEnd}
        onTouchCancel={this.onTouchEnd}
      >
        {this.props.children}
      </div>
    )
  }
}
