<template>
  <section class="flag-collection">
    <header>
      <h3 class="mdi mdi-folder-outline">{{collection.name}}</h3>
      <span
        class="mdi mdi-close"
        title="close"
        @click.prevent="onCloseFlagColl"
      />
    </header>
    <ul v-if="loadedItems">
      <li
        v-for="item in loadedItems"
        :key="item.id"
      >
        <MiniCard :item="item" :collid="collection.id"/>
      </li>
      <span v-if="loadedItems.length === 0">No items in your folder</span>
    </ul>
    <span v-else class="loading">Loading</span>
  </section>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import MiniCard from 'vuejs/components/Content/MiniCard'

export default {
  name: "FlagCollection",
  props: ['collection'],
  data: () => ({
    loadedItems: false
  }),
  computed: {
    ...mapState({
      flagcolls: state => state.User.flagcolls,
      flagcollsLoadedItems: state => state.User.flagcollsLoadedItems,
      openedCollid: state => state.User.openedCollid
    })
  },
  // watch: {
  //   flagcolls (newv, oldv) {
  //     console.log('watching flagcolls');
  //     if( typeof this.flagcolls[this.collection.id].loadedItems !== 'undefined' ) {
  //       this.loadedItems = this.flagcolls[this.collection.id].loadedItems
  //     }
  //   }
  // },
  created() {
    if (typeof this.flagcollsLoadedItems[this.openedCollid] !== 'undefined') {
      // if loadedItems are alredy loaded,
      // the mutation occurs before this subscription
      // so we first check if they are already available
      this.loadedItems = this.flagcollsLoadedItems[this.openedCollid]
    }

    this.unsubscribe = this.$store.subscribe((mutation, state) => {
      if (mutation.type === 'User/setLoadedCollItems') {
        console.log("mutation setLoadedCollItems collid", this.openedCollid)
        // mutation is triggered before the component update
        // so this.collection.id is not good
        this.loadedItems = state.User.flagcollsLoadedItems[this.openedCollid]
      }
    })

  },
  beforeDestroy() {
    this.unsubscribe()
  },
  // beforeMount () {
  //   if (typeof this.flagcolls[collection.id].loadedItems === 'undefined') {
  //     this.
  //   }
  // },
  methods: {
    ...mapActions({
      closeFlagColl: 'User/closeFlagColl'
    }),
    onCloseFlagColl(e) {
      this.closeFlagColl()
    }
  },
  components: {
    MiniCard
  }
}
</script>
<style lang="scss" scoped>
</style>
