import HTML2Canvas from 'html2canvas'
import Downloader from 'js-file-downloader'

export default {
  methods: {
    generateSignature() {
      this.generateState = this.$options.$_generateSteps[1]

      /**
       * Clone preview
       */
      const clone = document
        .querySelector('.brand-forms__tpl__content > div')
        .cloneNode(true)
      clone.setAttribute('id', 'clone-preview__bclh')
      clone.style.position = 'fixed'
      clone.style.top = '-99999px'
      clone.style.left = '-99999px'
      document.body.appendChild(clone)

      /**
       * Convert html to canvas
       */
      HTML2Canvas(document.getElementById('clone-preview__bclh'), {
        scale: 2,
        scrollX: 0,
        scrollY: 0,
        width: this.width,
        height: this.height
      }).then(canvas => {
        /**
         * Remove clone
         */
        clone.parentNode.removeChild(clone)

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

        /**
         * Post image to API
         */
        this.post('bclh/image/export', {
          image: img,
          type: this.extension
        })
          .then(res => {
            /**
             * Get file and download it
             */
            new Downloader({
              url: res.data.path,
              filename: `${this.filename}.${this.extension}`
            }).then(() => {
              this.generateState = this.$options.$_generateSteps[2]
              this.resetForm()

              setTimeout(() => {
                this.generateState = this.$options.$_generateSteps[0]
              }, 2000)
            })
          })
          .then(() => {
            // this.generateState = this.$options.$_generateSteps[3]
            //
            // setTimeout(() => {
            //   this.generateState = this.$options.$_generateSteps[0]
            // }, 2000)
          })
      })
    }
  }
}
