<template>
  <Sprite ref="sprite" texture="player" :x="position.x" :y="position.y" />
</template>

<script lang="ts" setup>
import { onPostUpdate, onPreUpdate, Sprite, useScene } from 'phavuer'
import { reactive, type Ref, ref } from 'vue'
import config from '@/config'
import { useSocketStore } from '@/stores/socket'

const socket = useSocketStore();

const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer,
  player: {
    type: Object,
    default: undefined
  },
})

const scene = useScene()

// onPreUpdate((time, delta) => {
//   console.log(time, delta);
// })

const position = reactive({ x: 0, y: 0 });

if (props.player !== undefined) {
  console.log('player', props.player);
  position.x = props.player?.coords.x;
  position.y = props.player?.coords.y;
}

const pointer_tile = ref(undefined);

function onPointerClick(pointer: Phaser.Input.Pointer) {
  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);
  if (pointer_tile.value) {
    const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y);
    position.x = worldPoint.x + config.tile_size.y;
    position.y = worldPoint.y;

    socket.socket?.emit('move', { x: position.x, y: 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');
  }

}

if (!props.player) {
  scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerClick);
}

socket.socket?.on('player_moved', (data) => {
  console.log('player_moved', data);

  if (data.id !== props.player?.id) {
    console.log('not you');
    return;
  }

  position.x = data.coords.x;
  position.y = data.coords.y;
})

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;
}
</script>