import {AdjustmentFilter} from '@pixi/filter-adjustment';
import {GlowFilter} from '@pixi/filter-glow';
import {Container} from '@pixi/react';
import {useEffect, useState} from 'react';

import {useEcs} from '@/context/ecs.js';
import {useMainEntity} from '@/context/main-entity.js';

import Entity from './entity.jsx';

export default function Entities({entities, filters}) {
  const [ecs] = useEcs();
  const [mainEntity] = useMainEntity();
  const [radians, setRadians] = useState(0);
  const [willInteractWith, setWillInteractWith] = useState(0);
  const [interactionFilters] = useState([new AdjustmentFilter(), new GlowFilter({color: 0x0})]);
  const pulse = (Math.cos(radians) + 1) * 0.5;
  interactionFilters[0].brightness = (pulse * 0.75) + 1;
  interactionFilters[1].outerStrength = pulse * 0.5;
  useEffect(() => {
    setRadians(0);
    const handle = setInterval(() => {
      setRadians((radians) => (radians + 0.1) % (Math.PI * 2))
    }, 50);
    return () => {
      clearInterval(handle);
    };
  }, [willInteractWith]);
  useEffect(() => {
    if (!mainEntity) {
      return;
    }
    setWillInteractWith(ecs.get(mainEntity).Interacts.willInteractWith);
  }, [entities, ecs, mainEntity]);
  const renderables = [];
  for (const id in entities) {
    if ('1' === id) {
      continue;
    }
    const isHighlightedInteraction = id == willInteractWith;
    renderables.push(
      <Entity
        filters={filters.concat(isHighlightedInteraction ? interactionFilters : [])}
        entity={entities[id]}
        key={id}
      />
    );
  }
  return (
    <Container
      sortableChildren
    >
      {renderables}
    </Container>
  );
}