#include "Emitter.h"
#include "olcUTIL_Geometry2D.h"
#include "utils.h"
#include "Crawler.h"
#include "DEFINES.h"

INCLUDE_game

LightningBoltEmitter::LightningBoltEmitter(vf2d startPos,vf2d endPos,float frequency,float timer,bool upperLevel)
	:startPos(startPos),endPos(endPos),Emitter(frequency,timer),upperLevel(upperLevel){}


void LightningBoltEmitter::Emit(){
	DrawLightningBolt();
}

void LightningBoltEmitter::DrawLightningBolt(){
	vf2d currentPos=startPos;
	const int MAX_ITERATIONS=100;
	geom2d::line<float>lineToTarget=geom2d::line<float>(startPos,endPos);
	float targetAngle=atan2(lineToTarget.vector().y,lineToTarget.vector().x);
	float targetDist=lineToTarget.length()*util::random(0.5);
	targetAngle+=util::random((PI/2))-PI/4;
	geom2d::line<float>lightningLine=geom2d::line<float>(currentPos,currentPos+vf2d{cos(targetAngle)*targetDist,sin(targetAngle)*targetDist});
	game->AddEffect(std::make_unique<Effect>(lightningLine.upoint(0),0,AnimationState::CHAIN_LIGHTNING,upperLevel,vf2d{lightningLine.length(),0.2},0.2,vf2d{},WHITE,targetAngle,0,true));
	int iterations=1;
	currentPos+=vf2d{cos(targetAngle)*targetDist,sin(targetAngle)*targetDist};
	while(iterations<MAX_ITERATIONS&&geom2d::line<float>(currentPos,endPos).length()>1){
		geom2d::line<float>lineToTarget=geom2d::line<float>(currentPos,endPos);
		float targetAngle=atan2(lineToTarget.vector().y,lineToTarget.vector().x);
		float targetDist=lineToTarget.length()*util::random(0.5);
		targetAngle+=util::random((PI/2))-PI/4;
		geom2d::line<float>lightningLine=geom2d::line<float>(currentPos,currentPos+vf2d{cos(targetAngle)*targetDist,sin(targetAngle)*targetDist});
		game->AddEffect(std::make_unique<Effect>(lightningLine.upoint(0),0,AnimationState::CHAIN_LIGHTNING,upperLevel,vf2d{lightningLine.length(),0.2},0.2,vf2d{},WHITE,targetAngle,0,true));
		currentPos+=vf2d{cos(targetAngle)*targetDist,sin(targetAngle)*targetDist};
		iterations++;
	}
}