<template>
  <div class='user-icon-form'>
    <input type='file' accept='image/*' ref='input' v-on:change='change'/>
    <div id='icon'>
      <img v-bind:src='value' v-if='value!=null'>
      <div id='noimage' v-else></div>
    </div>
    <div id='button'>
      <v-btn @click='clickForm'>Choose Icon</v-btn>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.user-icon-form{
  display: grid;
  grid-template-columns: 64px 180px;
  grid-gap: 16px;
  width: 260px;
  input {
    display: none;
  }
  #icon {
    width: 64px;
    height: 64px;
    border-radius: 32px;
    background: #0007;
    border: none;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
  #button {
    display: flex;
    align-items: center;
    width: 180px;
    label {
      height: 32px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
<script>

export default {
  props: ['value'],
  methods: {
    clickForm(){
      this.$refs.input.click();
    },
    change(event) {
      const file = event.target.files[0];
      const canvas = document.createElement('canvas');
      canvas.width = 128;
      canvas.height = 128;
      const ctx = canvas.getContext('2d');
      const image = new Image();
      image.onload = () => {
        const w = image.width;
        const h = image.height;
        let sx, sw, sh, sy;
        if(w > h) {
          sx = (w-h)/2
          sy = 0;
          sw = h;
          sh = h;
        }else{
          sy = (h-w)/2;
          sx = 0;
          sw = w;
          sh = w;
        }
        ctx.drawImage(image, sx, sy, sw, sh, 0, 0, 128, 128);
        this.value = canvas.toDataURL('image/jpeg');
        this.$emit('input', this.value);
      }
      image.src = URL.createObjectURL(file);
    }
  }
}
</script>
