<template>
  <DialogBase
    ref="dialogWindow"
    title="Move all albums..."
    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>
        <ArtistItem 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="artists.length == 0">
                Enter an artist name
              </h3>
              <ArtistItem
                class="ma8"
                v-for="artist in artists"
                :key="artist._id"
                :item="artist"
                @click="select(artist)"
                type="line"
              />
            </div>
          </template>
        </DropDown>
        <ArtistItem class="ma" :item="target" />
      </div>
    </div>
  </DialogBase>
</template>


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

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