import React from 'react'
import treeActions from 'actions/tree'
import newEventActions from 'actions/newEvent'
import newEventStores from 'stores/newEvent'

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

    this.state = {
      curNavIds: newEventStores.curNavIds,
      curNavId: newEventStores.curNavId
    }

    this.onEventChange = this.onEventChange.bind(this)
    this.curNavIdIndex = this.curNavIdIndex.bind(this)
    this.onClick = this.onClick.bind(this)
    this.isAllow = this.isAllow.bind(this)
    this.allowBackward = this.allowBackward.bind(this)
    this.allowForward = this.allowForward.bind(this)
  }

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

  componentWillUnmount() {
    this.unsubscribe()
  }

  onEventChange(status) {
    let obj = {}
    if (status && status.types) {
      if (status.types.includes('curNavIds')) {
        obj.curNavIds = status.data.curNavIds
      }
      if (status.types.includes('curNavId')) {
        if (this.state.curNavId !== status.data.curNavId) {
          obj.curNavId = status.data.curNavId
        }
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
      this.forceUpdate()
    }
  }

  curNavIdIndex() {
    let { curNavIds, curNavId } = this.state
    return curNavIds.findIndex(v => {
      return v.id === curNavId
    })
  }

  onClick(type) {
    let index = this.curNavIdIndex()
    let { curNavIds } = this.state
    let navInfo = undefined
    switch (type) {
      case 'backward':
        navInfo = curNavIds[index - 1]
        break
      case 'forward':
        navInfo = curNavIds[index + 1]
        break
    }
    if (navInfo) {
      treeActions.selectNode(navInfo.nodeId)
      newEventActions.toggleEventView({
        show: true,
        nodeId: navInfo.nodeId,
        mode: navInfo.mode,
        navId: navInfo.id
      })
    }
  }

  isAllow() {
    let { curNavIds, curNavId } = this.state
    return !!(curNavIds && curNavIds.length > 0 && curNavId)
  }

  allowBackward() {
    return this.isAllow() && !([-1, 0].indexOf(this.curNavIdIndex()) >= 0)
  }

  allowForward() {
    let { curNavIds } = this.state
    return (
      this.isAllow() &&
      !([-1, curNavIds.length - 1].indexOf(this.curNavIdIndex()) >= 0)
    )
  }

  render() {
    return (
      <div className="jenga-nav-navigate-nodes-wrap f--hlc">
        <button
          className="btn-clear btn-navigate-backward"
          disabled={!this.allowBackward()}
          onClick={this.onClick.bind(this, 'backward')}
        />
        <button
          className="btn-clear btn-navigate-forward"
          disabled={!this.allowForward()}
          onClick={this.onClick.bind(this, 'forward')}
        />
      </div>
    )
  }
}
