<template>
  <div class="kit__photo">
    <svg class="icon icon-add-plus" v-if="!imageUrl">
      <use xlink:href="/static/img/sprite.svg#icon-add-plus"></use>
    </svg>
    <img class="kit__photo-image" v-if="imageUrl" :src="imageUrl">
    <input type="file" class="kit__file" @change="onImageAdded">
  </div>
</template>

<script>
    import {api} from "../../js/modules/api";

    export default {
        name: "lil-image",
        props: ["imageId", "imageUrl", "accessToken"],
        data() {
            return {
                loading: false,
            }
        },
        methods: {
            onImageAdded(event) {
                this.loading = true;
                let file = event.target.files[0];
                let reader = new FileReader();
                reader.onload = () => {
                    api.uploadImage(reader.result, this.accessToken)
                        .then((response) => {
                            this.loading = false;
                            this.$emit('update:imageId', response.data.id);
                            this.$emit('update:imageUrl', response.data.image);
                        })
                        .catch((error) => {
                            this.loading = false;
                            console.log('error', error);
                        });
                };
                if (file) {
                    reader.readAsDataURL(file);
                }
            }
        }
    }
</script>

<style>
  .kit__photo-image {
    width: 140px;
    height: 110px;
    display: block;
    object-fit: contain;
  }
</style>