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

import {RESOLUTION} from '@/constants.js';
import {useEcs} from '@/context/ecs.js';
import {useMainEntity} from '@/context/main-entity.js';
import usePacket from '@/hooks/use-packet.js';

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

export default function EcsComponent() {
  const [ecs] = useEcs();
  const [entities, setEntities] = useState({});
  const [activeTool, setActiveTool] = useState(false);
  const [mainEntity] = useMainEntity();
  useEffect(() => {
    if (mainEntity) {
      ecs.get(mainEntity)
        .Wielder.activeItem()
          .then(({tool} = {}) => {
            setActiveTool(tool);
          });
    }
  }, [ecs, mainEntity]);
  usePacket('Tick', (payload) => {
    if (0 === Object.keys(payload.ecs).length) {
      return;
    }
    if (
      mainEntity
      && payload.ecs[mainEntity]
      && (payload.ecs[mainEntity].Inventory || payload.ecs[mainEntity].Wielder)
    ) {
      ecs.get(mainEntity)
        .Wielder.activeItem()
          .then(({tool} = {}) => {
            setActiveTool(tool);
          });
    }
    const updatedEntities = {...entities};
    for (const id in payload.ecs) {
      const update = payload.ecs[id];
      if (false === update) {
        delete updatedEntities[id];
      }
      else {
        updatedEntities[id] = ecs.get(id);
        if (update.Emitter?.emit) {
          updatedEntities[id].Emitter.emitting = {
            ...updatedEntities[id].Emitter.emitting,
            ...update.Emitter.emit,
          };
        }
      }
    }
    setEntities(updatedEntities);
  }, [ecs, entities, mainEntity]);
  if (!mainEntity) {
    return false;
  }
  const entity = ecs.get(mainEntity);
  const {Camera} = entity;
  const {TileLayers} = ecs.get(1);
  const [cx, cy] = [
    Math.round(Camera.x - RESOLUTION.x / 2),
    Math.round(Camera.y - RESOLUTION.y / 2),
  ];
  return (
    <Container
      x={-cx}
      y={-cy}
    >
      <TileLayer tileLayer={TileLayers.layers[0]} />
      {activeTool && (
        <TargetingGrid
          ecs={ecs}
          entity={entity}
        />
      )}
      <Entities entities={entities} />
      {activeTool && (
        <TargetingGhost
          ecs={ecs}
          entity={entity}
          projection={activeTool.projection}
        />
      )}
    </Container>
  )
}
