package pl.shockah.ts.particles;

import pl.shockah.glib.animfx.Animation;
import pl.shockah.glib.animfx.TimelineObject;
import pl.shockah.glib.geom.vector.IVector2;
import pl.shockah.glib.geom.vector.Vector2d;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.color.Color;
import pl.shockah.glib.gl.color.Colorf;
import pl.shockah.glib.particle.Particle;
import pl.shockah.glib.particle.ParticleSystem;
import pl.shockah.glib.particle.ParticleType;
import pl.shockah.ts.Assets;
import pl.shockah.ts.Main;

public class PtLand extends ParticleType {
	protected static final ParticleType pt = new PtLand();
	
	public static void make(ParticleSystem ps, Vector2d pos, Object... args) {
		pt.spawn(ps,pos,args);
	}
	
	public PtLand() {
		super(Assets.ptFuzzy);
	}
	
	public Particle create(ParticleSystem ps, IVector2 pos, Object... args) {
		CustomParticle cp = new CustomParticle(ps,this);
		cp.size.set(6d,6d);
		cp.pos = pos.toDouble();
		
		if (args.length == 0 || (args.length == 1 && args[0] instanceof Boolean)) {
			boolean b = args.length == 0 ? Main.rand.nextBoolean() : (boolean)args[0];
			cp.pos.x += b ? 10 : -10;
			cp.vel = Vector2d.make((.3d+(Main.rand.nextDouble()*.2d))*5d,Main.rand.nextDouble()*30d+(b ? 0d : 150d));
		} else if (args.length == 1 && args[0] instanceof Number) {
			Number n = (Number)args[0];
			cp.vel = Vector2d.make((.3d+(Main.rand.nextDouble()*.2d))*5d,n.doubleValue()-15d+Main.rand.nextDouble()*30d);
		}
		return cp;
	}
	
	protected void onUpdate(Particle p) {
		super.onUpdate(p);
		CustomParticle cp = (CustomParticle)p;
		
		cp.anim.update();
		if (cp.anim.isFinished()) cp.dead = true;
	}
	
	protected void onRender(Particle p, Graphics g) {
		CustomParticle cp = (CustomParticle)p;
		
		g.setColor(cp.tlColor.getState(cp.anim));
		image.scale = p.size.Div(image.getSize().toDouble());
		
		image.rotation.angle = p.rotation;
		g.draw(image,p.pos);
		image.rotation.angle = p.rotation+90;
		g.draw(image,p.pos);
		
		image.rotation.angle = 0;
		image.scale.set(1d,1d);
	}
	
	protected class CustomParticle extends Particle {
		protected final Animation anim = new Animation();
		protected final TimelineObject<Color> tlColor = new TimelineObject<>();
		
		public CustomParticle(ParticleSystem ps, ParticleType pt) {
			super(ps,pt);
			
			Color c = new Colorf(.9f,.9f,.9f);
			tlColor.add(c,0);
			tlColor.copyLast(6);
			tlColor.add(c.alpha(0f),12);
			anim.add(tlColor);
		}
	}
}