<template>
  <itf-button :icon="icon" :small="small" @click.stop="copy" :disabled="disabled">
    <slot>
      <itf-icon name="clipboard_copy" />
    </slot>
  </itf-button>
</template>
<script>
import { Vue, Component, Prop } from 'vue-property-decorator';
import itfIcon from '../icon/Icon';
import itfButton from '../button/Button';

export default @Component({
  components: {
    itfIcon,
    itfButton
  }
})
class CopyToClipboard extends Vue {
  @Prop(String) value;
  @Prop({ type: Boolean, default: true }) small;
  @Prop({ type: Boolean, default: true }) icon;
  @Prop({ type: Boolean, default: false }) disabled;

  async copy () {
    const showSuccess = this.$showSuccess;
    const showError = this.$showError;
    const $t = this.$t.bind(this);

    function fallbackCopyTextToClipboard (text) {
      const textArea = document.createElement('textarea');
      textArea.value = text;

      // Avoid scrolling to bottom
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.position = 'fixed';

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        if (document.execCommand('copy')) {
          showSuccess($t('components.copyToClipboard.copyingToClipboardWasSuccessful'));
        }
      } catch (err) {
        showError(err.message);
      }

      document.body.removeChild(textArea);
    }
    async function copyTextToClipboard (text) {
      if (!navigator.clipboard) {
        fallbackCopyTextToClipboard(text);
        return;
      }
      try {
        await navigator.clipboard.writeText(text);

        showSuccess($t('components.copyToClipboard.copyingToClipboardWasSuccessful'));
      } catch (err) {
        showError(err.message);
      }
    }

    await copyTextToClipboard(this.value);
  }
}
</script>
