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

import {usePacket} from '@/react/context/client.js';
import {useEcs, useEcsTick} from '@/react/context/ecs.js';
import {useMainEntity} from '@/react/context/main-entity.js';
import {useRadians} from '@/react/context/radians.js';

import Entity from './entity.jsx';

export default function Entities({monopolizers, particleWorker}) {
  const [ecs] = useEcs();
  const entities = useRef({});
  const [mainEntity] = useMainEntity();
  const radians = useRadians();
  const [willInteractWith, setWillInteractWith] = useState(0);
  const [interactionFilters] = useState([
    new AdjustmentFilter(),
    new GlowFilter({color: 0x0}),
  ]);
  const [, forceRender] = useState();
  useEffect(() => {
    if (!ecs || !particleWorker) {
      return;
    }
    async function onMessage(diff) {
      await ecs.apply(diff.data);
      for (const id in diff.data) {
        if (!diff.data[id]) {
          delete entities.current[id]
        }
        else {
          entities.current[id] = ecs.get(id);
        }
      }
      forceRender(Math.random());
    }
    particleWorker.addEventListener('message', onMessage);
    return () => {
      particleWorker.removeEventListener('message', onMessage);
    };
  }, [ecs, particleWorker]);
  const pulse = (Math.cos(radians / 4) + 1) * 0.5;
  interactionFilters[0].brightness = (pulse * 0.75) + 1;
  interactionFilters[1].outerStrength = pulse * 0.5;
  usePacket('EcsChange', async () => {
    entities.current = {};
  });
  const onEcsTickEntities = useCallback((payload, ecs) => {
    for (const id in payload) {
      if ('1' === id) {
        continue;
      }
      const update = payload[id];
      if (false === update) {
        delete entities.current[id];
        continue;
      }
      entities.current[id] = ecs.get(id);
    }
    forceRender(Math.random());
  }, []);
  useEcsTick(onEcsTickEntities);
  const onEcsTickParticles = useCallback((payload) => {
    for (const id in payload) {
      const update = payload[id];
      if (update.Emitter?.emit) {
        for (const id in update.Emitter.emit) {
          particleWorker?.postMessage(update.Emitter.emit[id]);
        }
      }
    }
  }, [particleWorker]);
  useEcsTick(onEcsTickParticles);
  const onEcsTickInteractions = useCallback((payload, ecs) => {
    const main = ecs.get(mainEntity);
    if (main) {
      setWillInteractWith(main.Interacts.willInteractWith);
    }
  }, [mainEntity]);
  useEcsTick(onEcsTickInteractions);
  const renderables = [];
  for (const id in entities.current) {
    const isHighlightedInteraction = 0 === monopolizers.length && id == willInteractWith;
    renderables.push(
      <Entity
        filters={isHighlightedInteraction ? interactionFilters : null}
        entity={entities.current[id]}
        key={id}
      />
    );
  }
  return (
    <Container
      sortableChildren
    >
      {renderables}
    </Container>
  );
}