<template>
  <v-expansion-panel-content>
    <template v-slot:header>
      <span class="subheading">{{ deck.name }}</span>
    </template>

    <v-alert v-if="!editing" :value="deck.note" type="info">
      {{ deck.note }}
    </v-alert>

    <v-container v-if="!editing" style="position: relative" grid-list-md fluid>
      <v-layout row wrap>
        <v-flex v-for="part in deck.parts()" :key="part.heading" xs12 sm6 md4>
          <v-card>
            <v-card-title>{{ part.count }} {{ part.heading }}</v-card-title>
            <v-list dense subheader>
              <Card
                v-for="card in part.cards"
                :key="card.serial"
                :count="card.count"
                :serial="card.serial"
                :dbentry="card.dbentry"
              ></Card>
            </v-list>
          </v-card>
        </v-flex>

        <v-btn fab absolute bottom right @click.native="editing = true">
          <v-icon>edit</v-icon>
        </v-btn>
      </v-layout>
    </v-container>

    <DeckEditor v-if="editing" :deck="deck" @save="save_deck">
      <v-btn color="error" @click.native="editing = false">
        <v-icon>cancel</v-icon>
        cancel
      </v-btn>
    </DeckEditor>
  </v-expansion-panel-content>
</template>

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

import Card from './Card.vue'
import DeckEditor from './forms/DeckEditor.vue'

export default {
  name: 'Deck',

  props: {
    deck: Object
  },

  components: {
    Card,
    DeckEditor
  },

  data: () => ({
    editing: false
  }),

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

  methods: {
    save_deck(new_deck) {
      axios
        .post('/decks/modify', {
          session: this.session,
          deckID: this.deck.id,
          deckCards: new_deck.plainObject()
        })
        .then(response => {
          if (response.data.success) {
            this.editing = false
            this.$emit('change')
          }
        })
    }
  }
}
</script>
