<template>
  <svg
    id="imageDetail"
    :viewBox="[0, 0, imageSize.width, imageSize.height].join(' ')"
  >
    <image :href="imageURL" @load="onImageLoaded" />
    <StickDetail
      v-for="(stick, stickID) in sticksByImageName"
      :key="stickID"
      :cameraID="cameraID"
      :imageName="imageName"
      :stickID="stickID"
      :showStick="showSticks"
      :showSnowMarker="showSnowMarkers"
      :showLabel="showLabels"
    />
  </svg>
</template>

<script>
import * as d3 from 'd3'
import StickDetail from '@/components/image-dialog/StickDetail.vue'
export default {
  name: 'ImageDetail',
  components: {
    StickDetail
  },
  props: {
    imageName: {
      type: String,
      required: true
    },
    cameraID: {
      type: String,
      required: true
    },
    showSnowMarkers: {
      type: Boolean,
      required: true
    },
    showLabels: {
      type: Boolean,
      required: true
    },
    showSticks: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      imageSize: {
        width: 1,
        height: 1
      },
      mousePressed: false,
      svgWidgetWidth: 0,
      svgWidgetHeight: 0,
      snowMarkerWidth: 120,
      snowMarkerHeight: 30,
      pivotPoint: { x: 0, y: 0 },
      selectedPart: null
    }
  },
  computed: {
    // --- D3 selectors ---
    $svg() {
      return d3.select('#imageDetail')
    },
    // ---

    // --- Vuex store data ---
    imageURL() {
      return this.$store.getters.imageURL(this.cameraID, this.imageName)
    },
    sticksByImageName() {
      return this.$store.getters.sticksByImageName(
        this.cameraID,
        this.imageName
      )
    },
    activeStick() {
      return this.$store.getters.activeStick
    },
    // ---

    // --- Zoom ---
    zoom() {
      return d3
        .zoom()
        .extent([
          [0, 0],
          [this.imageSize.width, this.imageSize.height]
        ])
        .translateExtent([
          [0, 0],
          [this.imageSize.width, this.imageSize.height]
        ])
        .scaleExtent([1, 4])
        .on('zoom', this.zoomed)
    }
    // ---
  },
  methods: {
    stickViewLabel(stickID) {
      return this.$store.getters.stickViewLabel(stickID, this.cameraID)
    },
    stickLengthCm(stickID) {
      return this.$store.getters.stickLengthCm(stickID)
    },
    zoomed({ transform }) {
      this.$svg.selectAll('image').attr('transform', transform)
      this.$svg.selectAll('g').attr('transform', transform)
    },
    onImageLoaded() {
      const img = new Image()
      img.src = this.imageURL
      this.imageSize.width = img.width
      this.imageSize.height = img.height
      this.$svg.call(this.zoom)
    }
  }
}
</script>

<style lang="scss" scoped>
#imageDetail {
  border-radius: 5px;
}
</style>
