<template>
  <Zone :originX="mapObj!.originX" :originY="mapObj!.originY" :width="mapObj?.frameWidth" :height="mapObj?.frameHeight" :x :y>
  </Zone>
</template>

<script lang="ts">
import { onPreUpdate, refObj, useScene, Zone } from 'phavuer'
import { calculateIsometricDepth } from '@/services/mapService'
import { defineComponent, onMounted, onUnmounted, type PropType } from 'vue'
import type { MapObject, PlacedMapObject } from '@/application/types'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import Image = Phaser.GameObjects.Image
const mapEditor = useMapEditorComposable()

export default defineComponent({
  components: { Zone },
  props: {
    obj: Object as PropType<PlacedMapObject>,
    mapObj: Object as PropType<MapObject>,
    x: Number,
    y: Number
  },

  setup(props) {
    const scene = useScene()
    const group = scene.add.group()

    const createImagePartition = (startX: number, endX: number, depthOffset: number) => {
      const img = scene.add.image(0,0, props.mapObj!.id!)

      img.setDepth(calculateIsometricDepth(props.obj!.positionX, props.obj!.positionY) + depthOffset)
      img.setOrigin(props.mapObj!.originX, props.mapObj!.originY)
      img.setCrop(startX, 0, endX, props.mapObj?.frameHeight)

      group.add(img)
    }

    onPreUpdate(() => {
      group.setXY(props.x!, props.y!)
      group.setAlpha(mapEditor.movingPlacedObject.value?.id == props.obj!.id || mapEditor.selectedMapObject.value?.id == props.obj!.id ? 0.5 : 1)
      group.setTint(mapEditor.selectedPlacedObject.value?.id == props.obj!.id ? 0x00ff00 : 0xffffff)
      group.getChildren().forEach((child) => {
        if (child as Image) {
          (child as Image).flipX = props.obj!.isRotated
        }
      })
    })

    group.setXY(props.x!, props.y!)
    createImagePartition(0, props.mapObj!.frameWidth * props.mapObj!.originX, -1)
    createImagePartition(props.mapObj!.frameWidth * props.mapObj!.originX, props.mapObj!.frameWidth, 1)

    onUnmounted(() => {
      group.destroy(true,true)
    })
  }
})

</script>