<template>
  <Container>
    <Rectangle 
      :x="props.character?.position_x"
      :y="props.character?.position_y" 
      :origin-x="0.5"
      :origin-y="12"
      :fillColor="0xFFFFFF"
      :width="74"
      :height="8"
    >
      <Rectangle
        :x="props.character?.position_x"
        :y="props.character?.position_y" 
        :origin-x="0.5"
        :origin-y="23.5"
        :fillColor="0x09ad19"
        :width="70"
        :height="4"
      />
    </Rectangle>
    <Text
      :text="props.character?.name"
      :x="props.character?.position_x"
      :y="props.character?.position_y" 
      :origin-x="0.5"
      :origin-y="3.5"
      :style="{
        fontFamily: 'Helvetica, Arial',
        color: '#FFF',
        fontSize: '1rem',
        strokeThickness: 4,
        stroke: '#000'
      }"
    />
    <Sprite ref="sprite" :x="props.character?.position_x" :y="props.character?.position_y" play="walk"  />
  </Container>
</template>

<script lang="ts" setup>
import { Container, Rectangle, Sprite, Text, useScene } from 'phavuer'
import { onBeforeMount, onMounted, reactive, type Ref, ref, watch } from 'vue'
import config from '@/config'
import { useSocketStore } from '@/stores/socket'
import { type Character as CharacterT } from '@/types'
import { useZoneStore } from '@/stores/zone'

const socket = useSocketStore()
const zone = useZoneStore();

const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer,
  character: Object as () => CharacterT
})

const scene = useScene()
const isSelf = props.character.id === socket.character.id;
const pointer_tile = ref()

onMounted(() => {
  if (isSelf) setupSelf()
});

function setupSelf()
{
  scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerClick)
}

function onPointerClick(pointer: Phaser.Input.Pointer) {
  if (!isSelf) return;

  const px = scene.cameras.main.worldView.x + pointer.x
  const py = scene.cameras.main.worldView.y + pointer.y

  pointer_tile.value = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile
  if (pointer_tile.value) {
    const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y)
    const position_x = worldPoint.x + config.tile_size.y
    const position_y = worldPoint.y
    socket.getConnection.emit('character:move', { position_x, position_y })
  }

  //Directions for player sprites + animations
  if (px < 0 && py > 0) {
    console.log('down left')
  } else if (px < 0 && py < 0) {
    console.log('top left')
  } else if (px > 0 && py > 0) {
    console.log('down right')
  } else if (px > 0 && py < 0) {
    console.log('top right')
  }
}

function getTile(x: number, y: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAtWorldXY(x, y)
  if (!tile) return undefined;
  return tile
}

/**
 * Resources:
 * https://www.youtube.com/watch?v=9sWrGohw9qo
 * https://jsfiddle.net/juwalbose/pu0gt7nc/
 *
 */
</script>
