package com.custardgames.hotel.entities.ecs.systems;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.utils.Array;
import com.custardgames.hotel.entities.ecs.components.Box2dBodyComponent;
import com.custardgames.hotel.entities.ecs.components.Box2dInteractionComponent;
import com.custardgames.hotel.entities.ecs.components.Box2dSpriteComponent;
import com.custardgames.hotel.entities.ecs.components.CharacterDataComponent;
import com.custardgames.hotel.entities.ecs.components.CharacterInputComponent;
import com.custardgames.hotel.entities.ecs.components.ObjectDataComponent;

public class CharacterInteractSystem extends EntityProcessingSystem
{
	@Mapper
	ComponentMapper<Box2dInteractionComponent> interactionComponents;
	@Mapper
	ComponentMapper<CharacterInputComponent> characterInputComponents;
	@Mapper
	ComponentMapper<CharacterDataComponent> characterDataComponents;

	@SuppressWarnings("unchecked")
	public CharacterInteractSystem()
	{
		super(Aspect.getAspectForAll(CharacterInputComponent.class, CharacterDataComponent.class, Box2dInteractionComponent.class));
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void process(Entity e)
	{
		Box2dInteractionComponent interactionComponent = interactionComponents.get(e);
		Array<Fixture> collisions = interactionComponent.getCollisions();

		CharacterInputComponent characterInput = characterInputComponents.get(e);
		CharacterDataComponent characterDataComponent = characterDataComponents.get(e);

		if (characterInput.isSpace())
		{
			if (characterDataComponent.isHasItem())
			{
				Entity item = characterDataComponent.getItem();
				item.getComponent(Box2dSpriteComponent.class).getSprite().setAlpha(1);
				characterDataComponent.removeItem();
				item.getComponent(ObjectDataComponent.class).removePlayer();
				item.getComponent(Box2dBodyComponent.class).getBody().applyForceToCenter(0.1f, 0.1f, true);
				characterInput.setSpace(false);
			}
			else
			{
				for (Fixture fixture : collisions)
				{
					if (fixture.getUserData() != null && fixture.getUserData().equals("interactive"))
					{
						if (((Entity) fixture.getBody().getUserData()).getComponent(ObjectDataComponent.class).isMoveable())
						{
							((Entity) fixture.getBody().getUserData()).getComponent(Box2dSpriteComponent.class).getSprite().setAlpha(0.5f);
							characterDataComponent.putItem((Entity) fixture.getBody().getUserData());
							((Entity) fixture.getBody().getUserData()).getComponent(ObjectDataComponent.class).putPlayer(e);
							characterInput.setSpace(false);
							break;
						}
					}
				}
			}
		}

	}

}
