<template>
  <div class="simple-file-upload">
    <a
      class="simple-file-upload__link"
      v-if="!value"
      @click="clickUploadCare">
      <document-icon class="simple-file-upload__icon"/>
    </a>
    <input
      type="hidden"
      role="uploadcare-uploader"
      name="file-upload"
      data-system-dialog
      ref="uploadcare-filedialog">
  </div>
</template>

<script>
  import uploadcareWidget from 'uploadcare-widget';

  import DocumentIcon from '@/components/icons/DocumentIcon';

  export default {
    props: ['value'],

    components: {
      DocumentIcon
    },

    mounted() {
      let widget = uploadcareWidget.Widget('[role=uploadcare-uploader]');

      widget.onChange(result => {
        result.done(fileInfo => {
          let urlWithFilename = fileInfo.cdnUrl + fileInfo.name;
          this.$emit('link-change-url', urlWithFilename);
        });
      });
    },

    methods: {
      clickUploadCare() {
        // workaround for styling the uploadcare widget
        let button = this.$el.querySelector('.uploadcare--widget__button');
        button.click();
      }
    },
  };
</script>

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

  .simple-file-upload {
    width: 25px;
    height: 25px;
    overflow: hidden;

    &__icon {
      width: 25px;
      fill: $color-silver-dark;
    }

    &__link {
      display: inline-block;
      overflow: hidden;
      width: 25px;
      height: 25px;
    }
  }

  /deep/ .uploadcare--widget {
    display: none;
  }
</style>
