import { isSafari } from '@/helpers/browser-detector'

export default {
  methods: {
    copyLink(link, callback, setOrigin = false) {
      let ret
      if (setOrigin) {
        link = window.location.origin + link
      }
      if (isSafari()) {
        // Create a new input tag element
        const el = document.createElement('input')
        el.value = link
        el.style.opacity = '0'
        el.id = 'i-device'
        // Apply the newly created element to the html body
        document.body.appendChild(el)
        // Make a copy of the original element properties
        const editable = el.contentEditable
        const readOnly = el.readOnly
        // Enable editable properties , highlight the range of the value
        el.contentEditable = true
        el.readOnly = false
        const range = document.createRange()
        range.selectNodeContents(el)
        const sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(range)
        el.setSelectionRange(0, 999999)
        // Reset the properties and run copy value to browser clipboard
        el.contentEditable = editable
        el.readOnly = readOnly
        ret = document.execCommand('copy')
        // Remove the input element
        if (document.getElementById('i-device')) {
          document.body.removeChild(el)
        }
      } else {
        var copy = function(e) {
          e.preventDefault()
          if (e.clipboardData) {
            e.clipboardData.setData('text/plain', link)
          } else if (window.clipboardData) {
            window.clipboardData.setData('Text', link)
          }
        }
        window.addEventListener('copy', copy)
        ret = document.execCommand('copy')
        window.removeEventListener('copy', copy)
      }
      if (callback) {
        callback(ret, link)
      }
    },
    defaultCopiedCallBack(response, link) {
      if (response) {
        this.$swal({
          title: this.$t('ShareQR.Copied'),
          type: 'success',
          timer: '1000',
          showConfirmButton: false,
        })
      } else {
        this.$swal({
          title: this.$t('ShareQR.Copied.Fail.Title'),
          text: this.$t('ShareQR.Copied.Fail.Msg'),
          input: 'text',
          inputValue: link,
          type: 'error',
        })
      }
    },
  },
}
