import React from 'react'
import uiActions from 'actions/ui'
import uiStores from 'stores/ui'
import newEventStores from 'stores/newEvent'

const minWidth = 920 // 最小宽度

export default class JengaDrag extends React.Component {
  constructor(props) {
    super(props)

    this.onEventChange = this.onEventChange.bind(this)
    this.getMinWidth = this.getMinWidth.bind(this)
    this.resetWidth = this.resetWidth.bind(this)

    this.onDragStart = this.onDragStart.bind(this)
    this.onDragEnd = this.onDragEnd.bind(this)
    this.onDragMove = this.onDragMove.bind(this)
  }

  componentDidMount() {
    this.resetWidth()
    this.unsubscribe = newEventStores.listen(this.onEventChange)
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  onEventChange(status) {
    if (status && status.types) {
      if (status.types.includes('showMemo')) {
        this.resetWidth()
      }
    }
  }

  getMinWidth() {
    return minWidth + (newEventStores.showMemo ? 150 : 0)
  }

  resetWidth(setViewWidth = true, afterSetWidth) {
    if (setViewWidth) {
      this.viewWidth = this.getMinWidth() + uiStores.jengaViewWidthDelta
    }
    let eventView = document.querySelector('.event-view')
    if (eventView) {
      eventView.style.width = this.viewWidth + 'px'
      afterSetWidth && afterSetWidth()
    }
  }

  onDragStart(e) {
    this.startX = e.pageX
    let curMinWidth = this.getMinWidth()
    this.startWidth =
      this.viewWidth > curMinWidth ? this.viewWidth : curMinWidth
    document.addEventListener('mousemove', this.onDragMove)
    document.addEventListener('mouseup', this.onDragEnd)
  }

  onDragEnd() {
    document.removeEventListener('mousemove', this.onDragMove)
    document.removeEventListener('mouseup', this.onDragEnd)
  }

  onDragMove(e) {
    this.viewWidth = this.startWidth + (e.pageX - this.startX)
    let curMinWidth = this.getMinWidth()
    if (this.viewWidth < curMinWidth) {
      this.viewWidth = curMinWidth
    }
    // 使用style的方式
    this.resetWidth(false, () => {
      // 通知其他相关组件去更新宽度
      uiActions.changeJengaViewWidthDelta({
        delta: this.viewWidth - this.getMinWidth()
      })
    })
  }

  render() {
    return <div className="jenga-drag" onMouseDown={this.onDragStart} />
  }
}
