import classnames from 'classnames'
import * as React from 'react'

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

interface Props extends React.ImgHTMLAttributes<HTMLImageElement> {
  isPad?: boolean
  onLongTouch?: () => void
}

export default class Img extends React.Component<Props, object> {
  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() {
    const { className, isPad, onLongTouch, ...props } = this.props
    return (
      <img
        onTouchStart={this.onTouchStart}
        onTouchEnd={this.onTouchEnd}
        onTouchCancel={this.onTouchEnd}
        className={classnames('ph-img', className, { 'is-pad': isPad })}
        {...props}
      />
    )
  }
}
