import {Container, Graphics} from '@pixi/react';
import {memo, useCallback} from 'react';

import {useDebug} from '@/context/debug.js';
import {useMainEntity} from '@/context/main-entity.js';

import Emitter from './emitter.jsx';
import Sprite from './sprite.jsx';

function Aabb({color, x0, y0, x1, y1}) {
  const draw = useCallback((g) => {
    g.clear();
    g.lineStyle(0.5, color);
    g.moveTo(x0, y0);
    g.lineTo(x1, y0);
    g.lineTo(x1, y1);
    g.lineTo(x0, y1);
    g.lineTo(x0, y0);
  }, [color, x0, x1, y0, y1]);
  return (
    <Graphics draw={draw} x={0.5} y = {0.5} />
  );
}

function Crosshair({x, y}) {
  const draw = useCallback((g) => {
    g.clear();
    g.lineStyle(1, 0x000000);
    g.moveTo(-5, 0);
    g.lineTo(5, 0);
    g.moveTo(0, -5);
    g.lineTo(0, 5);
    g.lineStyle(0.5, 0xffffff);
    g.moveTo(-5, 0);
    g.lineTo(5, 0);
    g.moveTo(0, -5);
    g.lineTo(0, 5);
    g.lineStyle(1, 0x000000);
    g.drawCircle(0, 0, 3);
    g.lineStyle(0.5, 0xffffff);
    g.drawCircle(0, 0, 3);
  }, []);
  return (
    <Graphics draw={draw} x={x} y={y} />
  );
}

function Entity({entity, ...rest}) {
  const [debug] = useDebug();
  const [mainEntity] = useMainEntity();
  if (!entity) {
    return false;
  }
  return (
    <Container
      zIndex={entity.Position?.y || 0}
    >
      {entity.Sprite && (
        <Sprite
          entity={entity}
          {...rest}
        />
      )}
      {entity.Emitter && (
        <Emitter
          entity={entity}
        />
      )}
      {debug && entity.Position && (
        <Crosshair x={entity.Position.x} y={entity.Position.y} />
      )}
      {debug && (
        <Aabb
          color={0xff00ff}
          x0={entity.VisibleAabb.x0}
          x1={entity.VisibleAabb.x1}
          y0={entity.VisibleAabb.y0}
          y1={entity.VisibleAabb.y1}
        />
      )}
      {debug && entity.Collider && (
        <Aabb
          color={0xffff00}
          x0={entity.Collider.aabb.x0}
          x1={entity.Collider.aabb.x1}
          y0={entity.Collider.aabb.y0}
          y1={entity.Collider.aabb.y1}
        />
      )}
      {debug && mainEntity == entity.id && (
        <Aabb
          color={0x00ff00}
          {...entity.Interacts.aabb()}
        />
      )}
    </Container>
  );
}

export default memo(Entity);
