<template>
  <div class="annotation-box" :style="style" @mousedown.stop.prevent @touchstart.stop.prevent>
    <div class="nw" @mousedown="resizeSelf('nw')" @touchstart="resizeSelf('nw')"></div>
    <div class="nn" @mousedown="resizeSelf('nn')" @touchstart="resizeSelf('nn')"></div>
    <div class="ne" @mousedown="resizeSelf('ne')" @touchstart="resizeSelf('ne')"></div>
    <div class="ww" @mousedown="resizeSelf('ww')" @touchstart="resizeSelf('ww')"></div>

    <div class="buttons">
      <template v-if="!immutable">
        <img alt="delete" src="@/assets/icons/trash.svg" @click="deleteSelf">
      </template>
    </div>

    <div class="ee" @mousedown="resizeSelf('ee')" @touchstart="resizeSelf('ee')"></div>
    <div class="sw" @mousedown="resizeSelf('sw')" @touchstart="resizeSelf('sw')"></div>
    <div class="ss" @mousedown="resizeSelf('ss')" @touchstart="resizeSelf('ss')"></div>
    <div class="se" @mousedown="resizeSelf('se')" @touchstart="resizeSelf('se')"></div>
  </div>
</template>

<script>
export default {
  name: "annotation-box",
  props: ['type', 'image', 'position', 'socket', 'immutable', 'boxUrl'],
  computed: {
    backgroundColor: function () {
      switch (this.type) {
        case 'server':
          return 'rgba(255, 0, 0, 0.3)';

        default:
          return 'rgba(255, 255, 255, 0.3)';
      }
    },
    style: function () {
      const left = this.image.left;
      const top = this.image.top;
      const width = this.image.width;
      const height = this.image.height;

      return {
        left: (left + this.position.x * width) + 'px',
        top: (top + this.position.y * height) + 'px',
        width: (this.position.w * width) + 'px',
        height: (this.position.h * height) + 'px',
        backgroundColor: this.backgroundColor
      }
    }
  },
  methods: {
    deleteSelf: function () {
      this.socket.post(this.boxUrl, {delete: true, id: this.id});
    },
    resizeSelf: function (mode) {
      this.$emit('resize', this.position, mode, this.updateSelf);
    },
    updateSelf: function (value) {
      this.socket.post(this.boxUrl, value);
    }
  }
}
</script>

<style scoped>
.annotation-box {
  position: absolute;

  display: grid;
  grid-template-rows: 10px auto 10px;
  grid-template-columns: 10px auto 10px;
}

.buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  width: 2rem;
  filter: invert(1);
  opacity: 0.9;
}

.nn, .ss {
  cursor: ns-resize;
}

.ww, .ee {
  cursor: ew-resize;
}

.ne, .sw {
  cursor: nesw-resize;
}

.nw, .se {
  cursor: nwse-resize;
}
</style>