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 TileLayer from './tile-layer.jsx';

function isEntityHoldingTool(entity) {
  const {Inventory, Wielder} = entity;
  const item = Inventory.item(Wielder.activeSlot + 1);
  return !!item && [
    '/assets/hoe',
  ].includes(item.source);
}

export default function EcsComponent() {
  const [ecs] = useEcs();
  const [entities, setEntities] = useState({});
  const [isTool, setIsTool] = useState(false);
  const [mainEntity] = useMainEntity();
  useEffect(() => {
    if (mainEntity) {
      setIsTool(isEntityHoldingTool(ecs.get(mainEntity)));
    }
  }, [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)
    ) {
      setIsTool(isEntityHoldingTool(ecs.get(mainEntity)));
    }
    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);
  }, [ecs, 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
      x={-cx}
      y={-cy}
    >
      <TileLayer tileLayer={TileLayers.layers[0]} />
      <Entities entities={entities} />
      {isTool && (
        <TargetingGhost
          x={Position.x}
          y={Position.y}
        />
      )}
    </Container>
  )
}
