import React from 'react'
import newEventStores from 'stores/newEvent'
import {
  nodeIsDyTransaction,
  nodeIsFunctionGroup,
  nodeIsIotMessage,
  nodeIsNormalService,
  nodeIsTimerService,
  nodeIsTransaction
} from 'stores/funcs/nodeType'
import { getEventNodeById } from 'stores/funcs/newEvent'
import NodeParams from './NodeParams'
import NodeServiceParams from './NodeServiceParams'
import TimerServiceParams from './TimerServiceParams'
import NodePublicService from './NodePublicService'
import NodeFuncGroup from './NodeFuncGroup'
import IotMessageConfig from './IotMessageConfig'

export default class JengaExtra extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      curEventNodeId: newEventStores.curEventNodeId,
      type: this.getType(newEventStores.curEventNodeId)
    }
    this.onEventChange = this.onEventChange.bind(this)
    this.getType = this.getType.bind(this)
  }

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

  componentWillUnmount() {
    this.unsubscribe()
  }

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

  getType(nodeId) {
    let type = null
    let node = getEventNodeById(nodeId)
    if (node) {
      if (nodeIsTimerService(node.type)) {
        type = 'timer'
      } else if (nodeIsTransaction(node.type)) {
        type = 'transaction'
      } else if (nodeIsDyTransaction(node.type)) {
        type = 'dyTransaction'
      } else if (nodeIsIotMessage(node.type)) {
        type = 'iotMessage'
      } else if (nodeIsNormalService(node.type)) {
        type = 'service'
      } else if (nodeIsFunctionGroup(node.type)) {
        type = 'funcGroup'
      }
    }
    return type
  }

  render() {
    return (
      <React.Fragment>
        {this.state.type === 'service' ? (
          <NodePublicService nodeId={this.state.curEventNodeId} />
        ) : this.state.type === 'funcGroup' ? (
          <NodeFuncGroup nodeId={this.state.curEventNodeId} />
        ) : null}
        {['funcGroup', 'transaction', 'dyTransaction'].indexOf(
          this.state.type
        ) >= 0 ? (
          <NodeParams nodeId={this.state.curEventNodeId} />
        ) : this.state.type === 'service' ? (
          <NodeServiceParams nodeId={this.state.curEventNodeId} />
        ) : this.state.type === 'timer' ? (
          <TimerServiceParams nodeId={this.state.curEventNodeId} />
        ) : this.state.type === 'iotMessage' ? (
          <IotMessageConfig nodeId={this.state.curEventNodeId} />
        ) : null}
      </React.Fragment>
    )
  }
}
