using Protogame;
using Protogame.ATFLevelEditor;
using Protoinject;

namespace SuperBallBrawlers
{
    public class PlayerSpawnerEntity : ComponentizedEntity
    {
        private readonly IEntityFactory _entityFactory;
        private readonly IHierarchy _hierarchy;

        private bool _spawned;
        private string _texture;
        private int _index;

        public PlayerSpawnerEntity(
            IEditorQuery<PlayerSpawnerEntity> editorQuery,
            IEntityFactory entityFactory,
            IHierarchy hierarchy)
        {
            _entityFactory = entityFactory;
            _hierarchy = hierarchy;

            editorQuery.DeclareAsEntity(this);
            editorQuery.MapTransform(this, x => Transform.Assign(x));
            editorQuery.UseModelForRendering(this, "model\\BaseBall.dae");

            editorQuery.MapCustom(this, "texture", "texture", x => _texture = x, "texture.BaseBall");
            editorQuery.MapCustom(this, "index", "index", x => _index = x, 0);

            _spawned = false;
        }

        public override void Update(IGameContext gameContext, IUpdateContext updateContext)
        {
            if (!_spawned)
            {
                var playerEntity = _entityFactory.CreatePlayerEntity(_texture, _index);
                playerEntity.SetStartPosition(Transform.LocalPosition);
                _hierarchy.MoveNode(_hierarchy.Lookup(gameContext.World), _hierarchy.Lookup(playerEntity));
                _spawned = true;
            }

            base.Update(gameContext, updateContext);
        }
    }
}
