<template>
  <v-container>
    <v-card flat>
      <v-alert :value="check.count !== 50" type="warning">
        {{ check.count }} cards detected! (Decks should have exactly 50 cards)
      </v-alert>
      <v-alert :value="check.maximum > 3" type="warning">
        Card with {{ check.maximum }} copies detected! (Cards should not have
        more than 3 copies)
      </v-alert>

      <v-textarea
        ref="deckList"
        :label="
          `${
            typeof deck !== 'undefined' && deck !== null ? 'Edit' : 'Paste'
          } Decklist`
        "
        rows="35"
        :hint="
          `ffdecks.com format – One card per line – Include quantity and serial (e.g. ${format_sample})`
        "
        style="font-family: monospace"
        :value="new_deck.deckList()"
        @input="check.checked = false"
      >
      </v-textarea>

      <v-card-actions>
        <slot></slot>
        <v-spacer></v-spacer>

        <v-btn color="info" @click.native="validate" :disabled="check.checked">
          <v-icon>check</v-icon>
          validate
        </v-btn>

        <v-btn color="success" @click.native="save" :disabled="!check.checked">
          <v-icon>save</v-icon>
          save
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-container>
</template>

<script>
import Deck from '@/classes/Deck'
import CardsDB from '@/plugins/ffdecks'

export default {
  name: 'DeckEditor',

  props: {
    deck: Object
  },

  data: () => ({
    check: null,
    new_deck: null
  }),

  computed: {
    format_sample() {
      let serials = []
      for (let tmp_key in CardsDB) {
        if (CardsDB.hasOwnProperty(tmp_key)) {
          serials.push(tmp_key)
        }
      }

      let quantity = Math.floor(Math.random() * 3) + 1
      let serial = serials[Math.floor(Math.random() * serials.length)]
      return `${quantity}x ${serial}`
    }
  },

  created() {
    this.clear()
  },

  methods: {
    clear() {
      this.check = {
        count: 50,
        maximum: 0,
        checked: false
      }

      this.new_deck = new Deck(0)
      if (this.deck)
        // this.deck should already be populated!
        this.new_deck.from_object(this.deck)
    },

    validate() {
      this.new_deck.from_deckList(this.$refs.deckList.lazyValue)
      this.new_deck.populate()

      // count number of cards
      this.check.count = this.new_deck.count()

      // find most frequent card
      this.check.maximum = 0
      for (let card of this.new_deck.cards) {
        if (card.count > this.check.maximum) this.check.maximum = card.count
      }

      // deck has now been checked
      this.check.checked = true
    },

    save() {
      this.$emit('save', this.new_deck)
    }
  }
}
</script>
