<template>
<section>
  <v-data-table dense
    :items="sources"
    :headers="headers">
    <template v-slot:item.updatedAt="{ item }">
      <span>{{new Date(item.updatedAt).toLocaleString()}}</span>
    </template>
    <template v-slot:item.actions="{ item }">
      <v-btn target="_blank" :href='`/api/source/${item.id}.rss`' small text color='orange' label='rss feed'><v-icon>mdi-rss</v-icon> Rss</v-btn>
      <v-btn @click='copy($event, item)' small text color='primary' label='embedd'><v-icon>mdi-application-brackets-outline</v-icon> Embed</v-btn>
    </template>
  </v-data-table>
  <p class='text-xl'>Add a website or a feed rss/atom/jsonfeed</p>
  <v-text-field v-model='url' outlined label='Add URL' required></v-text-field>
  <v-btn @click='addSource' :loading='loading' :error-messages='error' :disabled='loading'>Add</v-btn>
</section>
</template>
<script>
export default {
  data: () => ({
    url: '',
    error: '',
    loading: false,
    sources: [],
    headers: [
      {
        text: 'Actions',
        value: 'actions'
      },
      {
        text: 'Name',
        value: 'name',
      },
      {
        text: 'Description',
        value: 'description'
      },
      {
        text: 'Updated',
        value: 'updatedAt'
      },
    ]
  }),
  async fetch () {
    this.sources = await this.$http.$get('/api/source')
  },
  methods: {
    copy (ev, item) {
      console.error('dentro copy')
      const str = `<display-feed feed='${process.env.baseUrl}/api/source/${item.id}'></display-feed>`
      try {
        navigator.clipboard.writeText(str)
      } catch (e) {
        const el = document.createElement('textarea')
        el.addEventListener('focusin', e => e.stopPropagation())
        el.value = str
        document.body.appendChild(el)
        el.select()
        document.execCommand('copy')
        document.body.removeChild(el)
      }
    },
    async addSource() {
      this.loading = true
      this.error = false
      // add http if not specified
      this.url = this.url.match(/^https?:\/\//) ? this.url : 'http://' + this.url
      console.error(this.url)
      this.error = ''
      // invio un url al backend
      // se e' un feed valido, lo aggiungo ai sources e all cohort appena creata
      // se non e' valido provo a cercare il feed dentro quell'url
      try {
        const source = await this.$http.$post('/api/source', { URL: this.url })
        this.sources.unshift( source )
        // this.$emit('addCohort', { id: 1, title: this.title })
        // this.url = ''
      } catch (e) {
        this.error = String(e)
        console.error(this.error)
      }
      this.loading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.card {
  @apply w-full rounded-md border-2 border-dashed p-2 mt-3
    max-w-sm border-pink-500;
}
</style>