<template>
  <div class="kit__photo" :class="{ 'loading': loading, 'has-image': !! imageUrl }">
    <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";
    import downscale from 'downscale';

    export default {
        name: "lil-image",
        props: ["imageId", "imageUrl", "accessToken", "longSide"],
        data() {
            return {
                loading: false,

            }
        },
        methods: {
            onImageAdded(event) {
                this.loading = true;
                const longSide = +this.longSide || 1600;
                let file = event.target.files[0];
                const reader = new FileReader();
                reader.onload = () => {
                    let img = document.createElement('img');
                    img.onload = () => {
                        let w = 0;
                        let h = 0;
                        if(img.width > img.height) {
                            w = longSide;
                            h = 0;
                        }
                        else {
                            w = 0;
                            h = longSide;
                        }
                        downscale(img.src, w, h).then((dataURL) => {
                            img = null;
                            api.uploadImage(dataURL, this.accessToken)
                                .then((response) => {
                                    this.loading = false;
                                    this.$emit('update:imageId', response.data.id);
                                    this.$emit('update:imageUrl', response.data.image_thumbnail);
                                })
                                .catch((error) => {
                                    this.loading = false;
                                    console.log('error', error);
                                });
                        });
                    }
                    img.src = reader.result;
                };
                if (file) {
                    reader.readAsDataURL(file);
                }
            }
        }
    }
</script>

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