<template>
  <v-expansion-panel v-model="open">
    <NewDeck
      @change="
        open = null
        refresh_decks()
      "
    />

    <Deck
      v-for="deck in linked"
      :deck="deck"
      :key="deck.id"
      @change="refresh_decks"
    />
  </v-expansion-panel>
</template>

<script>
import * as Cookies from 'js-cookie'
import axios from '@/plugins/axios'
import DeckJS from '@/classes/Deck'

import Deck from './Deck.vue'
import NewDeck from './NewDeck.vue'

export default {
  name: 'DeckList',

  components: {
    Deck,
    NewDeck
  },

  data: () => ({
    open: null
  }),

  asyncComputed: {
    decks: {
      get() {
        return axios
          .post('/decks/list', {
            session: this.session
          })
          .then(response => {
            if (response.data.success) {
              return response.data.decks
            }
          })
      },
      default: []
    }
  },

  computed: {
    session: () => Cookies.get('session'),

    linked() {
      let result = []

      for (let plainDeck of this.decks) {
        let deck = new DeckJS(plainDeck.id)

        deck.from_object(plainDeck.content)
        deck.populate()

        result.push(deck)
      }

      result.sort((deck_l, deck_r) => deck_l.name.localeCompare(deck_r.name))
      return result
    }
  },

  methods: {
    refresh_decks() {
      this.$asyncComputed.decks.update()
    }
  }
}
</script>
