<template>
  <div>
    <h4>Center point</h4>
    <div class="asset-detail-center-point">
      <div class="card form-group">
        <div class="card-body">
          <div class="center-point-wrapper">
            <div class="image-wrapper">
              <img :src="imageUrl" @click="handleCenterPointClick" ref="image" draggable="false"/>
              <div v-if="relativeCenterPointStyle" class="center-point" :style="relativeCenterPointStyle"></div>
            </div>
            <div class="center-point-overlay"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .asset-detail-center-point {
    display: inline-block;
    width: 100%;
  }

  .center-point {
    position: absolute;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: solid white 2px;
    transform: translate(-50%, -50%);
    pointer-events: none;
    z-index: 1;

    &:before {
      content: '';
      position: absolute;
      left: 50%;
      top: 50%;
      width: 4px;
      height: 4px;
      background: white;
      border-radius: 50%;
      transform: translate(-50%, -50%);
    }

    &-wrapper {
      background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
      text-align: center;
    }

    &-overlay {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-color: black;
      opacity: 0.5;
      pointer-events: none;
    }
  }

  img {
    cursor: pointer;
    width: 100%;
    max-width: 600px;
  }

  .image-wrapper {
    position: relative;
    display: inline-block;
    max-width: 100%;
  }
</style>

<script>
import { ValueSyncMixin } from "../shared/value-sync-mixin";

export default {
  name: 'asset-detail-center-point',
  mixins: [ValueSyncMixin],
  props: {
    asset: {
      type: Object,
      required: true,
    },
    imageUrl: {
      type: String,
      required: true,
    },
    value: {
      type: Object,
      required: true,
    },
  },
  computed: {
    relativeCenterPointStyle() {
      if (this.asset && this.valueCopy) {
        return {
          left: `${this.valueCopy.x / this.asset.width * 100}%`,
          top: `${this.valueCopy.y / this.asset.height * 100}%`,
        }
      }
      return null;
    }
  },
  methods: {
    handleCenterPointClick(e) {
      const rect = this.$refs.image.getBoundingClientRect();
      const scale = this.asset.width / rect.width;
      const { offsetX, offsetY } = e;
      const x = Math.round(offsetX * scale);
      const y = Math.round(offsetY * scale);

      this.valueCopy = {
        x,
        y
      };
    }
  }
}
</script>
