<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 style="position: relative" grid-list-md fluid>
      <v-layout v-if="!editing" 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>
      <DeckEditor v-if="editing" :deck_list="deck_list" />
    </v-container>
  </v-expansion-panel-content>
</template>

<script>
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: {
    deck_parts() {
      let retval = ['Forwards', 'Backups', 'Summons, Monsters & more'].map(
        item => ({
          heading: item,
          cards: [],
          count: 0
        })
      )

      this.deck.cards.forEach(card => {
        let target
        switch (card.dbentry.type) {
          case 'Forward':
            target = 0
            break
          case 'Backup':
            target = 1
            break
          default:
            target = 2
            break
        }
        retval[target].cards.push(card)
        retval[target].count += card.count
      })

      retval.forEach(part =>
        part.cards.sort(
          (card_l, card_r) => card_l.dbentry.cost - card_r.dbentry.cost
        )
      )

      return retval
    },

    deck_list() {
      let lines = []

      // begin with deck name and note
      lines.push('Deck Name: ' + this.deck.name)
      lines.push(this.deck.note)
      lines.push('')

      // list forwards
      this.deck_parts.forEach(part => {
        lines.push(`${part.heading} (${part.count}):`)

        part.cards.forEach(card =>
          lines.push(`${card.count}x ${card.serial} "${card.dbentry.name}"`)
        )
        lines.push('')
      })

      return lines.join('\n')
    }
  }
}
</script>
