<!--

 This file is part of the Meeds project (https://meeds.io/).

 Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 3 of the License, or (at your option) any later version.
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public License
 along with this program; if not, write to the Free Software Foundation,
 Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

-->
<template>
  <v-hover>
    <v-alert
      v-if="errorMessage"
      type="error"
      class="position-static elevation-0"
      dismissible>
      {{ errorMessage }}
    </v-alert>
    <v-img
      slot-scope="{ hover }"
      :src="logoPreviewSrc" 
      role="presentation"
      transition="none"
      class="mx-auto"
      width="400"
      min-height="150"
      max-height="150"
      contain
      eager>
      <v-expand-transition>
        <div
          v-show="hover"
          class="justify-center light-grey-background absolute-full-size">
          <v-btn
            v-if="hover && !isDefaultSrc"
            color="error"
            class="absolute-all-center white error ma-auto"
            icon
            border
            outlined
            @click="resetLogo">
            <v-icon>fas fa-trash</v-icon>
          </v-btn>
          <v-file-input
            v-if="!resetInput"
            v-show="isDefaultSrc"
            id="logoFileInput"
            ref="logoFileInput"
            :loading="sendingImage"
            prepend-icon="fas fa-camera rounded-circle primary-border-color primary--text white py-1 absolute-all-center ma-auto"
            accept="image/*"
            class="branding-logo-selector"
            rounded
            clearable
            @change="uploadLogo" />
        </div>
      </v-expand-transition>
    </v-img>
  </v-hover>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: () => null,
    },
  },
  data: () => ({
    defaultLogoSrc: '/deeds-tenant-provisioning/rest/api/provisioning/settings/logo',
    logoSrc: null,
    sendingImage: false,
    maxFileSize: 2097152,
    resetInput: false,
    errorMessage: false,
  }),
  computed: {
    isDefaultSrc() {
      return !this.logoSrc;
    },
    logoPreviewSrc() {
      if (!this.logoSrc) {
        return this.defaultLogoSrc;
      }
      return this.logoSrc;
    },
  },
  watch: {
    logoPreviewSrc() {
      this.$emit('logo-src', this.logoPreviewSrc);
    },
    sendingImage() {
      if (this.sendingImage) {
        document.dispatchEvent(new CustomEvent('displayTopBarLoading'));
      } else {
        document.dispatchEvent(new CustomEvent('hideTopBarLoading'));
      }
    },
  },
  methods: {
    resetLogo() {
      this.logoSrc = null;
      this.$emit('input', null);
      this.sendingImage = false;
      if (this.$refs.logoFileInput) {
        this.resetInput = true;
        this.$nextTick().then(() => this.resetInput = false);
      }
    },
    uploadLogo(file) {
      if (file && file.size) {
        if (file.type && file.type.indexOf('image/') !== 0) {
          this.errorMessage = this.$t('deeds.provisioning.management.mustpng');
          return;
        }
        if (file.size > this.maxFileSize) {
          this.errorMessage = this.$t('deeds.provisioning.management.toobigfile');
          return;
        }
        this.sendingImage = true;
        const self = this;
        return this.$uploadService.upload(file)
          .then(uploadId => {
            if (uploadId) {
              const reader = new FileReader();
              reader.onload = (e) => {
                self.logoSrc = e.target.result;
                self.$forceUpdate();
              };
              reader.readAsDataURL(file);
              this.$emit('input', uploadId);
            } else {
              this.errorMessage = this.$t('deeds.provisioning.management.uploadingError');
            }
          })
          .catch(error => this.errorMessage = error)
          .finally(() => this.sendingImage = false);
      }
    },
  },
};
</script>