<template>
  <v-expansion-panel v-if="linked_decks">
    <Deck
      v-for="deck in linked_decks"
      :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 CardsDB from '@/plugins/ffdecks'

import Deck from './Deck.vue'

export default {
  name: 'DeckList',

  components: {
    Deck
  },

  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_decks() {
      let result = []

      for (let i = 0; i < this.decks.length; i++) {
        let elem = this.decks[i]
        let cards = []

        for (let j = 0; j < elem.content.cards.length; j++) {
          let card = elem.content.cards[j]

          cards.push({
            count: card.count,
            serial: card.serial,
            dbentry: CardsDB[card.serial]
          })
        }

        result.push({
          id: elem.id,
          name: elem.content.name,
          note: elem.content.note,
          cards: cards
        })
      }

      return result
    }
  },

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