<template>
  <div>
    <div>
      <label class="btn btn-b-n" style="width: 85px; height:40px;">
        Upload
        <input
          type="file"
          accept=".jpeg, .jpg, .gif, .png"
          value="Upload Photo"
          style="width: 0px;height: 0px;overflow: hidden;"
          name="images[]"
          @change="imagesAdd"
          :multiple="false"
          :disabled="!mayEdit"
        />
      </label>
    </div>
    <br />
    <div class="form-group row">
      <div v-for="(img, i) in image" class="col-md-2" :key="i">
        <img :src="img" style="height:200px; width:150px; object-fit: cover;" />
        <br />
        <span class="input-group-text" align="center" style="width:150px" @click="removeImage(key)">
          <eva-icon name="trash-2-outline" fill="#24aae1"></eva-icon>Delete
        </span>
      </div>
      <br />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    loadedImages: Function,
    mayEdit: { type: Boolean, default: () => true }
  },
  data() {
    return {
      images: {},
      image: [],
      imagesDefault: []
    };
  },
  methods: {
    imagesAdd(e) {
      if (!this.allowMultiple) {
        this.images = {};
        this.image = [];
      }

      const files = e.target.files || e.dataTransfer.files;

      this.images = [];
      Array.prototype.push.apply(this.images, files);
      if (!this.images.length) return;

      this.createImage(this.images);
      this.loadedImages(this.images);

      this.$emit("ImageLoaded", this.images);
    },

    createImage(file) {
      for (let i = 0; i < file.length; i++) {
        const reader = new FileReader();
        var vm = this;

        reader.onload = e => {
          vm.image.push(e.target.result);
        };
        reader.readAsDataURL(file[i]);
      }
    },

    removeImage(key) {
      this.image.splice(key, 1);
      this.images.splice(key, 1);

      if (!this.image.length) {
        this.$refs.im.value = "";
      }
    }
  }
};
</script>
