package pl.shockah.ts.entities.waterblur;

import java.util.List;
import pl.shockah.glib.geom.Rectangle;
import pl.shockah.glib.geom.Shape;
import pl.shockah.glib.geom.vector.Vector2d;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.logic.standard.Entities;
import pl.shockah.glib.logic.standard.EntityCollidable;
import pl.shockah.glib.logic.standard.EntityRenderable;
import pl.shockah.glib.logic.standard.Renderable;
import pl.shockah.ts.gameplay.Game;

public final class WaterBlur {
	public static final int blurLayers = 6;
	public static boolean blur = false;
	public static float blurAlpha = 1f;
	private static double sin = 0d;
	
	public static void toggle() {
		blur = !blur;
		blurAlpha = blur ? 1f/blurLayers : 1f;
	}
	
	public static void render(Graphics g) {
		toggle();
		sin += Game.me.time.getSpeed()/60d;
		
		double[] _blurAngle = new double[blurLayers], _blurDist = new double[blurLayers];
		Vector2d[] _v = new Vector2d[blurLayers];
		for (int i = 0; i < blurLayers; i++) {
			_blurAngle[i] = 360d/blurLayers*i+Math.sin(sin*Math.pow(i,1.2d))*(360d/blurLayers);
			_blurDist[i] = 1.5d+Math.sin(sin*Math.pow(i,.9d));
			_v[i] = Vector2d.make(_blurDist[i],_blurAngle[i]);
		}
		
		for (Renderable r : Entities.getRenderable()) {
			EntityRenderable er = r.getParent();
			if (er == null) continue;
			if (!(er instanceof IWaterBlur)) continue;
			if (isInWater((EntityCollidable)er)) {
				for (int i = 0; i < blurLayers; i++) {
					g.translate(-_v[i].x,-_v[i].y);
					r.render(g);
					g.translate(_v[i].x,_v[i].y);
				}
			}
		}
		
		toggle();
	}
	
	public static boolean isInWater(EntityCollidable e) {
		if (Game.me.cacheWaterShapes.isEmpty()) cacheWaterShapes();
		
		for (Shape shape : Game.me.cacheWaterShapes) if (e.collides(shape)) return true;
		return false;
	}
	private static void cacheWaterShapes() {
		List<Shape> list = Game.me.cacheWaterShapes;
		list.clear();
		
		for (int y = 0; y < Game.me.tileSize.y; y++) for (int x = 0; x < Game.me.tileSize.x; x++) {
			if (Game.me.water[x][y]) {
				boolean above = y != 0 && Game.me.water[x][y-1];
				list.add(new Rectangle(x*24,y*24+(above ? 0d : 6.5d),24,24-(above ? 0d : 6.5d)));
			}
		}
	}
}