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.audio.Music;
import com.badlogic.gdx.physics.box2d.Body;
import com.custardgames.hotel.entities.ecs.components.Box2dBodyComponent;
import com.custardgames.hotel.entities.ecs.components.MusicComponent;
import com.custardgames.hotel.events.BeginContactEvent;
import com.custardgames.hotel.managers.EventManager;

public class MusicSystem extends EntityProcessingSystem implements EventListener
{
	@Mapper
	ComponentMapper<Box2dBodyComponent> bodyComponents;
	@Mapper
	ComponentMapper<MusicComponent> musicComponents;

	private Music music;

	@SuppressWarnings("unchecked")
	public MusicSystem(Music music)
	{
		super(Aspect.getAspectForAll(Box2dBodyComponent.class, MusicComponent.class));
		EventManager.get_instance().register(BeginContactEvent.class, this);

		this.music = music;
	}

	@Override
	protected void process(Entity arg0)
	{

	}

	public void handleBeginContactEvent(BeginContactEvent e)
	{
		ImmutableBag<Entity> entities = getActives();
		for (int x = 0; x < entities.size(); x++)
		{
			Body body = bodyComponents.get(entities.get(x)).getBody();
			if (e.getFa().getBody() == body || e.getFb().getBody() == body)
			{
				if (e.getFa().getBody() == body)
				{
					if (e.getFb().getUserData().equals("player"))
					{
						music.stop();
						music.dispose();
						music = (Music) musicComponents.get(entities.get(x)).getMusic();
						music.setLooping(true);
						music.setVolume(1f);
						music.play();
					}
				}
				else
				{
					if (e.getFa().getUserData().equals("player"))
					{
						music.stop();
						music.dispose();
						music = (Music) musicComponents.get(entities.get(x)).getMusic();
						music.setLooping(true);
						music.setVolume(1f);
						music.play();
					}
				}
			}
		}
	}

}
