import React from 'react'
import cls from 'classnames'
import newEventActions from 'actions/event'
import newEventStores from 'stores/event'
import { getParentBlock, getEventNodeById } from 'stores/funcs/newEvent'
import { shallowEqualImmutable } from 'utils/utils'

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

    this.onToggleBlockEnable = this.onToggleBlockEnable.bind(this)
    this.hasAncestorBlockDisabled = this.hasAncestorBlockDisabled.bind(this)
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !shallowEqualImmutable(this.props, nextProps) ||
      !shallowEqualImmutable(this.state, nextState)
    )
  }

  onToggleBlockEnable() {
    if (!this.hasAncestorBlockDisabled()) {
      newEventActions.toggleBlockProp({
        nodeId: this.props.eventNodeId,
        blockId: this.props.bid,
        prop: 'skip'
      })
    }
  }

  hasAncestorBlockDisabled() {
    let eventNode = getEventNodeById(newEventStores.curEventNodeId)
    let hasDisabled = false
    if (eventNode && eventNode.events) {
      let result = eventNode.events.enable !== false
      hasDisabled = hasDisabled || !result
    }
    if (!hasDisabled) {
      let block = getParentBlock(this.props.bid, eventNode)
      while (!hasDisabled && block) {
        hasDisabled = hasDisabled || block.skip
        block = getParentBlock(block.ln, eventNode)
      }
    }
    return hasDisabled
  }

  render() {
    return (
      <button
        className={cls(
          'btn-clear btn-toggle-enable',
          this.props.isEnable ? 'btn-enable' : 'btn-disable',
          this.props.className ? this.props.className : ''
        )}
        style={this.props.style}
        onClick={this.onToggleBlockEnable}
      />
    )
  }
}
