<template lang="pug">
    .content_assets_index
          b-button(size='sm' variant='secondary' v-if='account' @click='importClick' class='mr-2') Import Testimonials
</template>
<script lang="ts">
import axios from 'axios'
import { flatfileImporter } from '@flatfile/sdk'

export default {
  data() {
    return {
      importer: null
    }
  },
  mounted() {
  
    // 
    //
    // 
    //
    // IF THIS COMPONENT IS LOADED MULTIPLE TIMES, THE
    // FLATFILE METHOD GETS CALLED FOR EACH ONE, CREATING 
    // DUPLICATE EVENT HANDLERS
    // 
    //
    // 
    //
    // 
    //
    
    console.log('Initializing Flatfile importer')
    axios
      .get('/app/api/tokens/import_testimonials')
      .then((response) => {
        this.importer = flatfileImporter(response.data.token)
        this.importer.on('error', (error) => {
          console.error(error)
        })
        this.importer.on('complete', this.handleFlatfileComplete)
      })
      .catch((e) =>
        console.error(
          'Flatfile jwt request failed. Are environment variables in place?',
          e
        )
      )
  },
  methods: {
    importClick() {
      console.log('import click')
      if (!this.importer) {
        alert('There was a problem initializing the importer.')
        return
      }
      this.importer.launch()
    },
    handleFlatfileComplete(payload) {
      //
      //
      //
      //
      // THIS IS CAN GET CALLED MULTIPLE TIMES ON THE SAME ROW
      //
      //
      //
      //
      
      const data = payload.data()
      const postData = {
        testimonials: data.rows.map((row) => {
          return {
            testimonial_text: row.data.testimonial_text,
            name: row.data.name,
            title: row.data.title,
            company: row.data.company,
            email: row.data.email,
            source: row.data.source,
            nps_score: row.data.nps_score,
          }
        }),
      }
      console.log('Flatfile data to POST', postData)
      axios.post('/app/api/content_assets/import.json', postData).then(
        (response) => {
          if (response.data.failures) {
            uiMessages.push(`⛔️ Uable to import ${response.data.failures} testimonials`)
          }
          if (response.data.successes) {
            uiMessages.push(`✅ ${response.data.successes} testimonials imported successfully`)
            console.log('Refreshing assets')
            setTimeout( () => {
              this.getContentAssets()
            }, 1000)
          }
          this.$toast(uiMessages.join(" "))
        }
      )
      .finally( () => {
      })
    },
  },
}
</script>
