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

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

<script>
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
  },

  props: {
    session: String
  },

  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: {
    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>
