package pl.shockah.ts.entities.waterblur;

import pl.shockah.glib.geom.Line;
import pl.shockah.glib.geom.Rectangle;
import pl.shockah.glib.geom.polygon.Polygon;
import pl.shockah.glib.gl.GL;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.Stencil;
import pl.shockah.glib.gl.StencilMask;
import pl.shockah.glib.gl.color.Color;
import pl.shockah.glib.logic.standard.EntityRenderable;
import pl.shockah.ts.gameplay.Game;

public class EffectWater extends EntityRenderable {
	private double sin = 0;
	
	public EffectWater() {
		baseDepth = -10001;
	}
	
	protected void onUpdate() {
		sin += Game.me.time.getSpeed()/60d;
	}
	protected void onRender(Graphics g) {
		StencilMask sm = new StencilMask(g,Stencil.Keep).proceed();
		for (int x = 0; x < Game.me.tileSize.x; x++) for (int y = 0; y < Game.me.tileSize.y; y++) if (Game.me.water[x][y]) drawWater(g,x,y,Color.White,Color.White);
		
		sm.proceed();
		WaterBlur.render(g);
		
		sm.proceed();
		Color cWater = Color.DarkCyan.alpha(.5f);
		Color cWaterLine = Color.Black;
		GL.setThickness(2);
		for (int x = 0; x < Game.me.tileSize.x; x++) for (int y = 0; y < Game.me.tileSize.y; y++) if (Game.me.water[x][y]) drawWater(g,x,y,cWater,cWaterLine);
		GL.setThickness(1);
	}
	protected void drawWater(Graphics g, int x, int y, Color cWater, Color cWaterLine) {
		double sx = x*24, sy = y*24;
		boolean U = y > 0 && Game.me.water[x][y-1];
		
		g.setColor(cWater);
		if (U) {
			g.draw(new Rectangle(x*24,y*24,24,24));
		} else {
			Polygon p = new Polygon(), p2 = new Polygon();
			for (int i = 0; i <= 12; i++) {
				double yy = sy+5+Math.sin(Math.toRadians(sx+i*2+sin*45)*4)*1.5d;
				p.addPoint(sx+i*2,yy);
				p2.addPoint(sx+i*2,yy+1);
			}
			p.addPoint(sx+24,sy+24);
			p.addPoint(sx,sy+24);
			g.draw(p);
			g.setColor(cWaterLine);
			for (Line line : p2.getLines(false)) g.draw(line);
		}
	}
}