package ei.game.gamestate;

import java.util.LinkedList;
import java.util.Queue;

import ei.engine.effects.ProgressBar;
import ei.engine.scene.Sprite;
import ei.engine.sound.SoundLoader;
import ei.engine.state.GameState;
import ei.engine.state.GameStateManager;
import ei.engine.texture.TextureLoader;

/**
 * This class handels the loading of the
 * images and sounds to the memmory.
 * 
 * @author Ziver
 */
public class LoadingState extends GameState{
	// The things to load
	private Queue<String> loadTextures;
	private Queue<String> loadSounds;
	//  The name of the next state to activate after loading
	private String nextState;
	private ProgressBar progress;

	
	/**
	 * Creates a loadingstate
	 * @param name The name of the state
	 */
	public LoadingState(String name,String nextState) {
		super(name);
		this.nextState = nextState;
		loadTextures = new LinkedList<String>();
		loadSounds = new LinkedList<String>();
		
		progress = new ProgressBar("Loading");
		progress.centerToScreen();
		progress.setBarTexture(new Sprite("ProgressBar","data/loadbar_front.png"));
		progress.setProgressTexture(new Sprite("Progress","data/loadbar.png"));
		progress.setBackgroundTexture(new Sprite("progressBackground","data/loadbar_back.png"));
	}
	
	/**
	 * Add a texture to be loaded
	 * @param url
	 */
	public void addTexture(String url){
		loadTextures.add(url);
		progress.setMax(loadTextures.size()+loadSounds.size());
	}
	
	/**
	 * Add a sound to be loaded
	 * @param url
	 */
	public void addSound(String url){
		loadSounds.add(url);
		progress.setMax(loadTextures.size()+loadSounds.size());
	}
	
	/**
	 * Loads the things
	 */
	public void update() {
		if(!loadTextures.isEmpty()){
			TextureLoader.getTextureLoaderInstance().getTexture(loadTextures.poll());
			progress.setValue(progress.getValue()+1);
		}
		else if(!loadSounds.isEmpty()){
			SoundLoader.getInstnace().loadSound(loadSounds.poll());
			progress.setValue(progress.getValue()+1);
		}
		else{
			progress.setValue(progress.getValue()+1);
			if(progress.getProcent() >= 100){
				//deactivate this state and activate the next one
				GameStateManager.getInstance().removeState(this);
				GameStateManager.getInstance().setActive(nextState);
			}			
		}
		progress.update();
	}
	
	/**
	 * Render the load bar
	 */
	public void render() {
		progress.render();
	}

}
