<template>
  <div
    class="document-form"
    ref="documentform">
    <div
      v-if="!value.url"
      ref="uploadcare-panel"/>
    <div
      class="document-form__uploaded"
      v-if="value.url">
      <document-icon class="document-form__icon"/>
      <a
        :href="previewUrl"
        class="document-form__link"
        target="_blank">{{ previewLink }}</a>
    </div>
  </div>
</template>

<script>
  import DocumentIcon from '@/components/icons/DocumentIcon';

  import {uploadcare} from '@/helpers/uploadcare';

  export default {
    props: ['value', 'index'],

    components: {
      DocumentIcon
    },

    computed: {
      previewUrl() {
        if (this.value && this.value.url) {
          return this.value.url;
        }
        return null;
      },
      previewLink() {
        if (this.value && this.value.url) {
          const parts = this.value.url.split('/');
          return parts[parts.length - 1];
        }
        return '';
      }
    },

    mounted() {
      uploadcare(this, url => {
        this.$emit('link-change-url', url, this.index);
      });
    },
  };
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .document-form {
    &__uploaded {
      display: flex;
      align-items: center;
    }

    &__link {
      text-decoration: underline;
    }

    &__icon {
      width: 30px;
      height: 30px;
      margin-right: $small-spacing;
    }

    &__file-input {
      width: 0.1px;
      height: 0.1px;
      overflow: hidden;
      opacity: 0;
      position: absolute;
      z-index: -1;

      & + label {
        cursor: pointer;
        background-color: $color-silver-light;
        height: 150px;
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
        font-family: $sans-serif-font-family;
        font-weight: $font-weight-regular;
        text-decoration: underline;
      }
    }
  }
</style>
