<template>
  <div>
    <CollectQuotesExplain />
    <AddNewQuote v-if="quotes.length > 0" @createQuote="createQuote"/>
    <NoQuotesYet v-if="quotes.length == 0" />
    <QuoteListItem
      v-for="quote in quotes"
      :key="quote.id"
      :quote="quote"
      @editQuote="editQuote"
    />
    <AddNewQuote @createQuote="createQuote" />
    <CollectQuote
      v-if="showCollectQuoteDialog"
      :quote="collectQuote"
      @close="closeCollectQuoteDialog"
      @saveQuote="saveQuote"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      showCollectQuoteDialog: false,
      collectQuote: {},
    }
  },
  computed: {
    quotes() {
      var quotes = [...this.$store.state.myQuotes.quotes]
      quotes.sort((a, b) => {
        return a.id.localeCompare(b.id)
      })
      return quotes
    },
  },
  methods: {
    closeCollectQuoteDialog() {
      this.showCollectQuoteDialog = false
    },
    editQuote(quote) {
      this.showCollectQuoteDialog = true
      this.collectQuote = {
        id: quote.id,
        quote: quote.quote,
      }
    },
    async saveQuote(quote) {
      this.showCollectQuoteDialog = false
      await this.$engine.saveQuote(quote.id, quote.quote)
      await this.$engine.getMyQuotes()
    },
    createQuote() {
      this.showCollectQuoteDialog = true
      this.collectQuote = {
        id: ':new:',
        quote: '',
      }
    },
  },
  async fetch() {
    await this.$engine.getMyQuotes()
  },
}
</script>
