<template>
  <div class="copy-to-clipboard-container">
    <transition
      :css="false"
      mode="out-in"
      @afterEnter="afterEnter"
    >
      <div
        v-if="showMessage"
        ref="message"
        class="message"
      >
        {{ message }}
      </div>
    </transition>
    <ui-icon-button
      class="copy-button"
      button-type="button"
      :icon="icon"
      :disabled="disabled"
      :disable-ripple="true"
      @click.stop="copyToClipboard(text)"
    />
  </div>
</template>
<script>

const { UiIconButton } = window.kiln.utils.components;

export default {
  components: {
    UiIconButton
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      required: true
    },
    icon: {
      type: String,
      default: 'link'
    },
    message: {
      type: String,
      default: 'Copied!'
    },
    messageTimeout: {
      type: Number,
      default: 250
    }
  },
  data() {
    return {
      showMessage: false
    };
  },
  methods: {
    copyToClipboard(url) {
      const el = document.createElement('textarea');

      el.value = url;
      el.setAttribute('readonly', '');
      el.style.position = 'absolute';
      el.style.opacity = 0;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);

      this.showMessage = true;
    },
    afterEnter() {
      setTimeout(() => {
        this.showMessage = false;
      }, this.messageTimeout);
    }
  }
};
</script>
<style lang="scss" scoped>
  @import 'Styles/colors.scss';

  .copy-to-clipboard-container {
    display: inline-block;
    position: relative;
    top: -1px;
  }

  .ui-icon-button {
    border-radius: 0;
    height: 1.125rem;
    width: 1.5rem;

    &:active:not(.is-disabled) {
      transform: scale(0.8, 0.8);
    }

    &.ui-icon-button--type-primary {
      background-color: transparent;

      &.ui-icon-button--color-default:hover:not(.is-disabled) {
        background-color: transparent;
      }
    }

    /deep/ .ui-icon {
      font-size: 1.125rem;
    }

    &.is-disabled {
      /deep/ .ui-icon-button__icon {
        color: $disable-color;
      }
    }
  }

  .message {
    font-size: 10px;
    position: absolute;
    right: -40px;
    top: 0;
  }

  @keyframes fade-in-out {
    0% {
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }
</style>
