import Vue from 'vue'
import './SntPaymentUpload.scss'
import { VCard, VImg, VFadeTransition } from 'vuetify/lib'
import imgEmpty from '../../assets/img/img-empty.png'

export default Vue.extend({
  name: 'SntPaymentUpload',
  components: { VCard, VImg, VFadeTransition },
  props: {
    value: {
      type: Object,
      default: undefined
    }
  },
  data () {
    return {
      imageLocalUrl: null,
      files: [],
      edit: false
    }
  },
  computed: {
    imgWithDefault () {
      return this.imageLocalUrl || imgEmpty
    }
  },
  methods: {
    inputFile (newFile, oldFile) {
      if (newFile && !oldFile) {
        this.$nextTick(() => {
          const fileObj = this.files[0]
          this.imageLocalUrl = fileObj.url
          this.$emit('input', fileObj.file)
        })
      }
    },
    inputFileFilter (newFile, oldFile, prevent) {
      this.error = null
      if (newFile && !oldFile) {
        if (!/\.(gif|jpg|jpeg|png|webp)$/i.test(newFile.name)) {
          this.error = '* Your choice is not a picture'
          return prevent()
        }
      }
      if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
        // eslint-disable-next-line no-param-reassign
        newFile.url = ''
        const URL = window.URL || window.webkitURL
        if (URL && URL.createObjectURL) {
          // eslint-disable-next-line no-param-reassign
          newFile.url = URL.createObjectURL(newFile.file)
        }
      }
      return null
    }
  },
  template: `
    <snt-image
      :src="imgWithDefault"
      width="280px"
      height="300px">
      <div
        class="snt-payment__wrapper">
        <svg-camera
          width="50"
          fill="#ffffff" />
        <div>
          <snt-button
            for="payment-upload"
            class="snt-payment__upload"
            tag="label"
            text
            dark>
            เลือกรูปภาพ
          </snt-button>
          <file-upload
            ref="paymentUpload"
            v-model="files"
            :drop="!edit"
            name="payment-upload"
            extensions="gif,jpg,jpeg,png,webp"
            accept="image/png,image/gif,image/jpeg,image/webp"
            @input-filter="inputFileFilter"
            @input-file="inputFile" />
        </div>
      </div>
    </snt-image>
  `
})
