<template>
  <BaseCollapsibleCard v-if="isShownNodeSelection">
    <template #header-title
      >Selection</template
    >
    <template #header-right>
      <i
        class="el-icon-close clickable-icon"
        style="float: right; padding: 3px 0"
        @click="clearCloseNodeSelection"
      ></i>
    </template>

    <template #content>
      <section v-if="selectedNodes.length > 0" class="limit-height-scrollable">
        <div
          v-for="node in getNodesByIds(selectedNodes)"
          :key="`${node.id}`"
          @click="
            DESELECT_NODES([node.id])
            UNSET_NODE_HIGHLIGHT(node.id)
          "
        >
          <Node
            :data-id="node.id"
            :visuals="{
              baseNodeRadius: 11,
              groupNodeRadiusDifference: 2,
              smallLabel: true,
              showLabel: true
            }"
            :allow-hover="true"
          ></Node>
        </div>
      </section>
      <section v-else>Select nodes with left click.</section>

      <div class="buttons">
        <b-button
          :disabled="selectedNodes.length > 1 ? chosenAction === 'group' : true"
          size="is-small"
          type="is-dark"
          @click="prepareGroup()"
          >Make group</b-button
        >

        <b-button
          :disabled="selectedNodes.length > 1 ? chosenAction === 'alias' : true"
          size="is-small"
          type="is-dark"
          @click="prepareAlias()"
          >Make alias</b-button
        >

        <span v-if="isSelectingRepresentativeNode">
          <br />Select representative node for bundle or
          <a @click="isSelectingRepresentativeNode = false">cancel</a>.
        </span>
        <b-button
          v-else
          :disabled="selectedNodes.length === 0"
          size="is-small"
          type="is-dark"
          @click="
            prepareBundle()
            resetAggregationCommit()
          "
          >Bundle to …</b-button
        >

        <b-button size="is-small" type="is-dark" @click="showTagCreation"
          >Create selection</b-button
        >

        <b-button size="is-small" type="is-dark" @click="clearCloseNodeSelection()"
          >Clear selection</b-button
        >
      </div>

      <div v-if="isChoosingAggregationName">
        <b-field>
          <b-input v-model="aggregationLabel" placeholder="Enter a label"></b-input>
          <p class="control">
            <b-button
              :disabled="aggregationLabel.length === 0"
              class="button is-info"
              @click="commitAggregation"
              @keyup.enter="commitAggregation"
              >Save</b-button
            >
          </p>
          <b-button type="is-text" style="margin-left: 0.3em" @click="resetAggregationCommit()"
            >X</b-button
          >
        </b-field>
      </div>
    </template>
  </BaseCollapsibleCard>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
import Node from '@/components/Tools/Node/Node.vue'

export default {
  components: { Node },

  data() {
    return {
      isChoosingAggregationName: false,
      chosenAction: undefined,
      aggregationLabel: '',
      isSelectingRepresentativeNode: false,
      previouslySelectedNodes: []
    }
  },

  computed: {
    ...mapState('interaction', ['selectedNodes']),
    ...mapGetters('interaction', ['isShownNodeSelection']),
    ...mapGetters('data', ['getNodesByIds'])
  },

  watch: {
    selectedNodes(arr) {
      if (arr.length === 0) this.resetAggregationCommit()
    }
  },

  methods: {
    ...mapActions('interaction', ['clearCloseNodeSelection', 'hideTagCreation', 'showTagCreation']),
    ...mapActions('data', ['groupNodes', 'aliasNodes', 'bundleNodes', 'tagNodes']),
    ...mapMutations('interaction', ['DESELECT_NODES', 'UNSET_NODE_HIGHLIGHT']),

    prepareBundle() {
      this.isSelectingRepresentativeNode = true
      this.previouslySelectedNodes = []
      this.selectedNodes.forEach(id => this.previouslySelectedNodes.push(id))
    },
    prepareGroup() {
      this.isChoosingAggregationName = true
      this.chosenAction = 'group'
    },
    prepareAlias() {
      this.isChoosingAggregationName = true
      this.chosenAction = 'alias'
    },
    commitAggregation() {
      if (this.chosenAction === 'group') {
        this.groupNodes({ nodes: this.selectedNodes, label: this.aggregationLabel })
        this.clearCloseNodeSelection()
      } else if (this.chosenAction === 'alias') {
        this.aliasNodes({ nodes: this.selectedNodes, label: this.aggregationLabel })
        this.clearCloseNodeSelection()
      } else {
        throw Error('Invalid action')
      }
      this.chosenAction = undefined
      this.isChoosingAggregationName = false
      this.aggregationLabel = ''
    },
    resetAggregationCommit() {
      this.chosenAction = undefined
      this.isChoosingAggregationName = false
      this.aggregationLabel = ''
    }
  },

  mounted() {
    this.$store.subscribe(mutation => {
      if (mutation.type === 'interaction/SELECT_NODE' && this.isSelectingRepresentativeNode) {
        if (this.previouslySelectedNodes.includes(mutation.payload)) {
          this.$buefy.toast.open({
            duration: 4000,
            message: `Cannot bundle to selected node.`,
            position: 'is-top',
            type: 'is-danger'
          })
        } else {
          this.bundleNodes({
            representativeNodeId: mutation.payload,
            nodeIds: this.previouslySelectedNodes
          })
          this.isSelectingRepresentativeNode = false
          this.clearCloseNodeSelection()
        }
      }
    })
  }
}
</script>

<style lang="sass" scoped>
@import ../_workspace
section
  font-size: 0.9em
  margin-bottom: 0.7em
  &.limit-height-scrollable
    max-height: 20em
    overflow-y: auto

.card-right
  width: $card-right-width
  margin-bottom: 20px

.el-card__header
  padding: 12px 10px

.item
  margin-bottom: 18px

.clickable-icon
  cursor: pointer

.header-title
  padding: 10px
  margin-top: 50px
  position: relative
  top: 5px

.card-header-btn
  float: right
  padding: 8px 4px

.clearfix:before,
.clearfix:after
  display: table
  content: ''

.clearfix:after
  clear: both
</style>
