<template>
  <div class="image-form">
    <div
      class="image-form__error"
      v-if="hadError">
      Ups, das scheint kein Bild zu sein. Bitte versuche es nochmal mit einer anderen Datei, oder lade die Datei als <a
        class="image-form__link"
        @click="switchToDocument">Dokument</a> hoch.
    </div>

    <div
      v-if="!value.url"
      ref="uploadcare-panel"/>
    <div v-if="value.url && !hadError">
      <img
        :src="previewUrl"
        @error="error">
    </div>
  </div>
</template>

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

  export default {
    props: ['value', 'index'],
    data() {
      return {
        hadError: false,
        uploadcarePanel: null,
        url: '',
        filename: ''
      };
    },
    computed: {
      previewUrl: function () {
        if (this.value && this.value.url) {
          return this.value.url + '-/preview/200x200/';
        }
        return null;
      }
    },
    mounted() {
      this.mountUploadcare();
    },
    methods: {
      error(e) {
        this.hadError = true;
        delete this.value.url;

        setTimeout(() => {
          this.mountUploadcare();
        }, 0);
      },
      mountUploadcare() {
        this.uploadcarePanel = uploadcare.openPanel(this.$refs['uploadcare-panel'], null, {
          tabs: ['file'],
        });

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

          panelResult.progress(p => {
          });

          panelResult.fail(uploadResult => {
          });
        });
      },
      switchToDocument() {
        this.$emit('switch-to-document', this.index, {
          url: `${this.url}${this.filename}`
        });
      }
    }
  };
</script>

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

  .image-form {
    &__error {
      @include regular-text;
      margin-bottom: $medium-spacing;
      line-height: 1.5;
    }

    &__link {
      text-decoration: underline;
      @include regular-text;
      cursor: pointer;
    }

    &__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>
