<script setup>
import { ref, computed } from 'vue'
import { postImage } from './api.js'

const emit = defineEmits(['OnImageUpload'])
const props = defineProps({
  name: String,
})

const imagePath = ref(null)
const error = ref(null)

function onFileChanged(e) {
  postImage(e.target.files[0])
    .then((res) => res.json())
    .then((json) => onJsonResult(json))
    .catch((err) => (error.value = err['error']))
}

function onJsonResult(json) {
  imagePath.value = json['filepath']
  emit('OnImageUpload', json['fileId'])
}

function unsetImage() {
  imagePath.value = null
}

const imageSrc = computed(() => {
  return 'http://localhost:8080' + imagePath.value
})
</script>

<template>
  <div v-if="imagePath">
    <div class="relative">
      <figure class="image mb-3">
        <img v-bind:src="imageSrc" v-bind:alt="props.name" />
      </figure>
      <span class="icon is-large" @click="unsetImage">
        <b-icon-x-circle-fill />
      </span>
    </div>
  </div>
  <div v-else class="file">
    <label class="file-label">
      <input
        class="file-input"
        @change="onFileChanged"
        type="file"
        :name="props.name"
        accept="image/*"
      />
      <span class="file-cta">
        <span class="file-icon">
          <b-icon-upload />
        </span>
        <span class="file-label">{{ $t('addbook.coverupload') }}</span>
      </span>
    </label>
  </div>
</template>

<style scoped>
img {
  max-height: 500px;
  max-width: 500px;
  height: auto;
  width: auto;
}
.relative {
  position: relative;
}

.relative img {
  display: block;
}

.relative .icon {
  position: absolute;
  bottom: 5px;
  left: 5px;
  background-color: rgba(0, 0, 0, 0.7);
  font-size: 24px;
  border-radius: 5px;
}

.relative .icon:hover {
  background-color: rgba(0, 0, 0, 0.8);
  cursor: pointer;
}
</style>
