import {useState} from 'react';
import {useEcs, useEcsTick} from '@/context/ecs.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) {
        for (const key in dialogue) {
          updatedEntities[id].Interlocutor.dialogues[key] = dialogue[key];
        }
      }
    }
    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}
    </>
  );
}
