<template>
  <div class="legend"
       :id="'legend' + this.node.id"
       :class="{
           'start-legend': node.type === 'StartNode',
           'end-legend': node.type === 'EndNode',
           'node-legend': node.type === 'Node',
           'action-legend': node.type === 'ActionNode',
           'active-node': active
         }"
       @mouseup="handleMouseUp"
       @mousedown="handleMouseDown">
    <span class="legend-text">{{ this.node.name }}</span>
    <div class="legend-ep up-ep" v-if="node.type !== 'EndNode'"></div>
    <div class="legend-ep down-ep" v-if="node.type !== 'EndNode'"></div>
    <div class="legend-ep left-ep" v-if="node.type !== 'EndNode'"></div>
    <div class="legend-ep right-ep" v-if="node.type !== 'EndNode'"></div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { initLegend } from './legendUtil.js'
import { clearActiveConnection } from './connectionUtil.js'

export default {
  computed: mapGetters({
    operationItem: 'operationItem'
  }),
  methods: {
    handleMouseDown () {
      if (this.active) {
        return
      }

      const instance = window._jsPlumbInstance

      clearActiveConnection(this.operationItem, instance)

      this.$store.dispatch('changeOperationItem', {
        id: this.node.id,
        type: this.node.type
      })
    },
    handleMouseUp () {
      this.$store.dispatch('movePosition', {
        id: this.node.id,
        top: parseInt(this.$el.style.top.replace('px', '')),
        left: parseInt(this.$el.style.left.replace('px', ''))
      })
    }
  },
  created () {},
  watch: {
    'node.top' (val) {
      this.$el.style.top = val + 'px'
    },
    'node.left' (val) {
      this.$el.style.left = val + 'px'
    }
  },
  mounted () {
    this.$el.style.left = this.node.left + 'px'
    this.$el.style.top = this.node.top + 'px'

    const instance = window._jsPlumbInstance

    const init = () => {
      initLegend(instance, this.$el)

      setTimeout(() => {
        if (this.node.lines) {
          for (let i = 0; i < this.node.lines.length; i++) {
            let connection = instance.connect({
              source: 'legend' + this.node.id,
              target: 'legend' + this.node.lines[i].target,
              type: 'basic'
            })
            connection.getOverlay('label').setLabel(this.node.lines[i].name)
          }
        }
      }, 100)
    }

    instance.batch(init.bind(this))
  },
  props: {
    node: {
      type: Object,
      required: true,
      default: function () {
        return {}
      }
    },
    active: {
      type: Boolean,
      required: true
    }
  }
}
</script>

<style>

</style>
