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

import java.util.EventListener;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.systems.EntityProcessingSystem;
import com.artemis.utils.ImmutableBag;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.custardgames.hotel.entities.ecs.components.Box2dInteractionComponent;
import com.custardgames.hotel.events.BeginContactEvent;
import com.custardgames.hotel.events.EndContactEvent;
import com.custardgames.hotel.managers.EventManager;

public class Box2dInteractionSystem extends EntityProcessingSystem implements EventListener
{
	@Mapper
	ComponentMapper<Box2dInteractionComponent> interactionComponents;

	@SuppressWarnings("unchecked")
	public Box2dInteractionSystem()
	{
		super(Aspect.getAspectForAll(Box2dInteractionComponent.class));
		EventManager.get_instance().register(BeginContactEvent.class, this);
		EventManager.get_instance().register(EndContactEvent.class, this);
	}

	@Override
	protected void process(Entity arg0)
	{
		// TODO Auto-generated method stub

	}

	public void handleBeginContactEvent(BeginContactEvent e)
	{
		ImmutableBag<Entity> entities = getActives();
		for (int x = 0; x < entities.size(); x++)
		{
			Fixture fixture = interactionComponents.get(entities.get(x)).getInteractionFixture();
			if (e.getFa() == fixture || e.getFb() == fixture)
			{
				if (e.getFa() == fixture)
				{
					interactionComponents.get(entities.get(x)).addFixture(e.getFb());
				}
				else
				{
					interactionComponents.get(entities.get(x)).addFixture(e.getFa());
				}
			}
		}
	}

	public void handleEndContactEvent(EndContactEvent e)
	{
		ImmutableBag<Entity> entities = getActives();
		for (int x = 0; x < entities.size(); x++)
		{
			Fixture fixture = interactionComponents.get(entities.get(x)).getInteractionFixture();
			if (e.getFa() == fixture || e.getFb() == fixture)
			{
				if (e.getFa() == fixture)
				{
					interactionComponents.get(entities.get(x)).removeFixture(e.getFb());
				}
				else
				{
					interactionComponents.get(entities.get(x)).removeFixture(e.getFa());
				}
			}
		}
	}
}
