import {Sprite} from '@pixi/react';
import {useState} from 'react';

import {RESOLUTION} from '@/constants.js'
import Ecs from '@/engine/ecs.js';
import usePacket from '@/hooks/use-packet';

export default function EcsComponent() {
  const [ecs] = useState(new Ecs());
  const [entities, setEntities] = useState({});
  const [mainEntity, setMainEntity] = useState();
  usePacket('Tick', (payload) => {
    if (0 === Object.keys(payload.ecs).length) {
      return;
    }
    ecs.apply(payload.ecs);
    const updatedEntities = {...entities};
    for (const id in payload.ecs) {
      if (false === payload.ecs[id]) {
        delete updatedEntities[id];
      }
      else {
        updatedEntities[id] = ecs.get(id);
        if (updatedEntities[id].MainEntity) {
          setMainEntity(ecs.get(id));
        }
      }
    }
    setEntities(updatedEntities);
  }, [entities]);
  if (!mainEntity) {
    return false;
  }
  const {Camera} = mainEntity;
  const [cx, cy] = [Camera.x - RESOLUTION.x / 2, Camera.y - RESOLUTION.y / 2];
  const sprites = [];
  for (const id in entities) {
    const entity = entities[id];
    sprites.push(
      <Sprite
        image={entity.Sprite.image}
        key={id}
        x={entity.Position.x - cx}
        y={entity.Position.y - cy}
      />
    );
  }
  return (
    <>
      {sprites}
    </>
  )
}
