<template>
  <DialogBase
    ref="dialogWindow"
    title="Move all videos..."
    buttonText="Move"
    buttonClass="accept"
    @accept="merge"
    @closed="closed"
    :closeOnButtonClick="false"
    :enableFooterButtons="acceptable"
  >
    <div class="flex-row" id="merge-content">
      <div class="flex-column">
        <h4 class="ma-left ma-top">From</h4>
        <BoxItem class="ma" :item="source" />
      </div>
      <awesome-icon id="arrow-icon" icon="arrow-right" />
      <div class="flex-column">
        <DropDown class="ma-left ma-top">
          <input
            type="search"
            v-model="search"
            @search="searchTermChanged"
            placeholder="Into"
          />
          <template v-slot:dropdown-content>
            <div class="flex-column">
              <h3 class="ma" v-if="boxes.length == 0">Enter an box title</h3>
              <BoxItem
                class="ma8"
                v-for="box in boxes"
                :key="box._id"
                :item="box"
                @click="select(box)"
                type="line"
              />
            </div>
          </template>
        </DropDown>
        <BoxItem class="ma" :item="target" />
      </div>
    </div>
  </DialogBase>
</template>


<script>
export default {
  data() {
    return {
      boxes: [],
      search: "",
      searchTimer: 0,
      source: {},
      target: { covers: {} },
    };
  },
  methods: {
    closed() {
      this.boxes = [];
      this.source = {};
      this.target = { covers: {} };
      this.search = "";
      clearTimeout(this.searchTimer);
    },
    open(source) {
      this.source = source;
      this.$refs.dialogWindow.open();
    },
    merge() {
      this.$store
        .dispatch("boxes/move", {
          source: this.source._id,
          target: this.target._id,
        })
        .then(() => {
          this.$store.dispatch("boxes/loadBox", this.target._id);
          this.$store.dispatch("boxes/selectBoxById", this.target._id);
          this.$store.dispatch("boxes/remove", this.source._id);
          this.$refs.dialogWindow.close();
        });
    },
    searchTermChanged() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.$store.dispatch("boxes/filter", this.search).then((result) => {
          this.boxes = result;
        });
      }, 250);
    },
    select(album) {
      this.target = album;
    },
  },
  computed: {
    acceptable() {
      return this.source._id != undefined && this.target._id != undefined;
    },
  },
};
</script>

<style scoped>
input {
  width: 128px;
}
#arrow-icon {
  align-self: center;
}
#merge-content {
  align-items: flex-end;
}
</style>