package pl.shockah.ts.states;

import pl.shockah.Util;
import pl.shockah.glib.AssetLoader;
import pl.shockah.glib.Gamelib;
import pl.shockah.glib.geom.vector.Vector2i;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.color.Color;
import pl.shockah.glib.gl.tex.Image;
import pl.shockah.glib.logic.standard.GameStandard;
import pl.shockah.glib.state.State;
import pl.shockah.glib.state.View;
import pl.shockah.glib.state.transitions.TransitionThroughColor;
import pl.shockah.ts.Assets;

public class StateLoading extends State {
	protected boolean once = true;
	
	public StateLoading() {
		views.add(new View(new Vector2i(960,720)));
	}
	
	protected void onPreUpdate() {
		if (!once) return;
		once = false;
		
		AssetLoader al = Assets.createAssetLoader();
		Graphics g = GameStandard.me.getGraphics();
		
		while (true) {
			al.update();
			
			if (al.finished()) {
				Assets.setupAssets();
				State.change(new StateMenuMain(),new TransitionThroughColor(.025f),new TransitionThroughColor(.025f,true));
				break;
			}
			
			if (Assets.ssLoadingBar != null) {
				g.clear();
				drawLoadingBar(g,al.getStatus());
				Gamelib.advanceFrame();
			}
			
			Util.sleep(1);
		}
	}
	
	protected void onPreTransitionRender(Graphics g) {
		drawLoadingBar(g,1d);
	}
	
	private void drawLoadingBar(Graphics g, double status) {
		Vector2i size = getDisplaySize();
		
		g.setColor(Color.White);
		Image image = Assets.ssLoadingBar.getImage(0);
		Image image2 = image.part(0,0,(int)(image.getWidth()*status),(int)image.getHeight());
		image2.offset.set(Assets.ssLoadingBar.offset);
		g.draw(image2,(size.x-image.getWidth())/2,size.y/2-image.getHeight()/2);
		g.draw(Assets.ssLoadingBar.getImage(1),(size.x-image.getWidth())/2,size.y/2-image.getHeight()/2);
	}
}