import { http } from '@inside-library/helpers/Http'
import HTML2Canvas from 'html2canvas'
import JsFileDownloader from 'js-file-downloader'

export default {
  $_i18nRootPath: 'customs.HOMEPAGE.dashboard',
  methods: {
    generateDashboard(title, client) {
      /**
       * Clone preview
       */
      const clone = document
        .querySelector('.homepage-dashboard-container')
        .cloneNode(true)
      clone.setAttribute('id', 'clone-preview-ecen')
      clone.style.position = 'fixed'
      clone.style.top = '-99999px'
      clone.style.left = '-99999px'
      document.body.appendChild(clone)

      /**
       * Convert html to canvas
       */
      const rect = clone.getBoundingClientRect()

      HTML2Canvas(document.querySelector('#clone-preview-ecen'), {
        scale: 2,
        scrollX: 0,
        scrollY: 0,
        width: rect.width,
        height: rect.height
      }).then(canvas => {
        /**
         * Remove clone
         */
        clone.parentNode.removeChild(clone)

        /**
         * Convert canvas to image
         */
        const img = canvas.toDataURL('image/jpeg', 1)

        /**
         * Display export and edit buttons
         */
        this.showEdit = true

        /**
         * Post image to API
         */
        try {
          http
            .post('ecen/image/export', {
              image: img,
              type: this.extension
            })
            .then(res => {
              /**
               * Get file and download it
               */
              new JsFileDownloader({
                url: res.path,
                filename: `${title} - ${client} - ${
                  this.$_currentLang === 'en'
                    ? 'Cockpit Performance'
                    : 'Indicateurs de performance'
                }.pdf`
              })
            })
        } catch (err) {
          throw new Error(err)
        }
      })
    }
  }
}
