import {Assets} from '@pixi/assets';
import {Sprite as PixiSprite} from '@pixi/react';
import {useEffect, useState} from 'react';

export default function Sprite({entity}) {
  const [asset, setAsset] = useState();
  useEffect(() => {
    const asset = Assets.get(entity.Sprite.source);
    if (asset) {
      setAsset(asset);
    }
    else {
      Assets.load(entity.Sprite.source).then(setAsset);
    }
  }, [setAsset, entity.Sprite.source]);
  if (!asset) {
    return false;
  }
  let texture;
  if (asset.textures) {
    const animation = asset.animations[entity.Sprite.animation]
    texture = animation[entity.Sprite.frame];
  }
  else {
    texture = asset;
  }
  return (
    <PixiSprite
      texture={texture}
      x={entity.Position.x}
      y={entity.Position.y}
    />
  );
}