<template>
    <div v-if="visible" class="cropped-image">
      <div id="close_btn" class="btn"
        @mousedown.prevent="close"
        @touchstart.prevent="close">
        <img alt="close button" src="@/assets/icons/cross.svg">
      </div>
      <div class="image-container" :style="style">
        <div v-if="box">
          <h3>{{labelName}}</h3>
          <img :src="src" ref="crop" alt="crop" />
        </div>
        <div v-else>Select a crop to show</div>
      </div>
    </div>


</template>

<script>
    export default {
        name: "cropped-image",
        props: ["width", "margin", "labels"],


        // mounted: function() {}
        // destroyed: function() {}

        data: function() {
            return {
                visible: false,
                box: null,
            }
        },

        computed: {
          src: function () {
            if (!this.box)
              return ''
            var width = this.width - 2 * this.margin /*padding*/;
            return this.$root.socket.url(`/results/${this.box.identifier}/crop/${width}x${width}`)
          },

          style: function() {

            return {
              minWidth: `${this.width}px`,
              margin: `${this.margin}px`,
            }

          },
          labelName: function() {
            if (!this.box)
              return ''

            if (this.box.label == null)
              return 'Unknown'

            let name = 'Not Found';
            for (let label of this.labels){
              if (label.identifier != this.box.label)
                continue;

              name = label.name;
              break;
            }
            return name
          },

        },

        methods: {
            toggle: function () {
              this.set_visible(!this.visible);
            },

            set_visible: function (visible) {
              this.visible = visible;

              if (!visible)
                this.box = null;

              this.$emit("visibility-change", visible);
            },

            show: function (box_element) {
              this.box = box_element.box;
            },

            close: function() {
              this.set_visible(false);
              this.$emit("closed");
            }
        },
    }
</script>

<style scoped>

.cropped-image {
  height: 100%;

  background-color: rgba(133, 133, 133, 0.7);
}

.image-container {
  /*align-items: center;*/
  justify-content: center;
  text-align: center;
  display: flex;
}

.image-container img {
  border-width: 2px;
  border-style: solid;
}

#close_btn {
  justify-content: right;
  text-align: right;

  margin:  5px;
}

</style>
