<template>
  <div class="document-form" ref="documentform">
    <div v-if="!value.url" ref="uploadcare-panel"></div>
    <div v-if="value.url">
      <a :href="previewUrl">{{previewUrl}}</a>
    </div>
  </div>
</template>

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

  export default {

    props: ['value', 'index'],
    mounted() {
      const uploadcarePanel = uploadcare.openPanel(this.$refs['uploadcare-panel'], null, {
        tabs: ['file'],
      });

      // HACK to change the text of the Uploadcare dynamically we need to change the text here directly
      setTimeout(() => {
        const formElem = this.$refs['documentform'];
        if (formElem.getElementsByClassName('uploadcare--text_size_extra-large').length > 1) {
          formElem.getElementsByClassName('uploadcare--text_size_extra-large')[1].innerText = 'Ziehen Sie ein Dokument hier hinein';
          formElem.getElementsByClassName('uploadcare--tab__action-button')[0].innerText = 'Wählen Sie ein lokales Dokument';
        }
      }, 0);

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

        panelResult.progress(p => {
        });

        panelResult.fail(uploadResult => {
        });
      });
    },
    computed: {
      previewUrl: function() {
        if (this.value && this.value.url) {
          return this.value.url;
        }
        return null;
      }
    }
  }
</script>

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

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

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