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

import {RESOLUTION} from '@/constants.js';
import {useMainEntity} from '@/context/main-entity.js';
import Ecs from '@/ecs/ecs.js';
import Components from '@/ecs-components/index.js';
import Systems from '@/ecs-systems/index.js';
import usePacket from '@/hooks/use-packet.js';

import Entities from './entities.jsx';
import TargetingGhost from './targeting-ghost.jsx';
import TileLayer from './tile-layer.jsx';

export default function EcsComponent() {
  const [ecs] = useState(new Ecs({Components, Systems}));
  const [entities, setEntities] = useState({});
  const [mainEntity] = useMainEntity();
  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);
      }
    }
    setEntities(updatedEntities);
  }, [entities, mainEntity]);
  if (!mainEntity) {
    return false;
  }
  const {Camera, Position} = ecs.get(mainEntity);
  const {TileLayers} = ecs.get(1);
  const [cx, cy] = [
    Math.round(Camera.x - RESOLUTION.x / 2),
    Math.round(Camera.y - RESOLUTION.y / 2),
  ];
  return (
    <Container>
      <TileLayer
        tileLayer={TileLayers.layers[0]}
        x={-cx}
        y={-cy}
      />
      <Entities
        entities={entities}
        x={-cx}
        y={-cy}
      />
      <TargetingGhost
        px={Position.x}
        py={Position.y}
        cx={cx}
        cy={cy}
      />
    </Container>
  )
}
