import {useState} from 'react';

import {useEcs, useEcsTick} from '@/context/ecs.js';
import {parseLetters} from '@/dialogue.js';

import Entity from './entity.jsx';

export default function Entities({camera, scale}) {
  const [ecs] = useEcs();
  const [entities, setEntities] = useState({});
  useEcsTick((payload) => {
    if (!ecs) {
      return;
    }
    const updatedEntities = {...entities};
    for (const id in payload) {
      if ('1' === id) {
        continue;
      }
      const update = payload[id];
      if (false === update) {
        delete updatedEntities[id];
        continue;
      }
      updatedEntities[id] = ecs.get(id);
      const {dialogue} = update.Interlocutor || {};
      if (dialogue) {
        const {dialogues} = updatedEntities[id].Interlocutor;
        for (const key in dialogue) {
          updatedEntities[id] = ecs.rebuild(id);
          dialogues[key] = dialogue[key];
          dialogues[key].letters = parseLetters(dialogues[key].body);
          dialogues[key].onClose = () => {
            delete dialogues[key];
            setEntities((entities) => ({
              ...entities,
              [id]: ecs.rebuild(id),
            }));
          };
        }
      }
    }
    setEntities(updatedEntities);
  }, [ecs, entities]);
  const renderables = [];
  for (const id in entities) {
    renderables.push(
      <Entity
        camera={camera}
        entity={entities[id]}
        key={id}
        scale={scale}
      />
    );
  }
  return (
    <>
      {renderables}
    </>
  );
}
