#include <allegro.h>

#include "main.h"

#include "ball.h"
#include "line.h"

Line *Line::lines = 0;

Line *bottomref = 0, *leftref = 0, *rightref = 0;

Line *left = 0;
Line *right = 0;
Line *lefttop = 0;
Line *righttop = 0;

Line::Line(float _xp, float _yp, float _xp2, float _yp2, int _sound) : Part(_xp, _yp, 0, 0) {
		
	rp = atan2(_yp2 - _yp, _xp2 - _xp);
	R = sqrt(pow(_yp2 - _yp, 2) + pow(_xp2 - _xp, 2));
	
	nextline = lines;
	lines = this;	
	
	sound = _sound; // metal
		
}

Line::~Line() { // Only ever delete all at once
	lines = 0;
}

Line::Line(float _xp, float _yp, float _rp, float _R) : Part(_xp, _yp, _rp, _R) {
	nextline = lines;
	lines = this;		
}

bool Line::ballcollision(Ball *b, float *nx, float *ny, float *sx, float *sy, float *d) {
	float bx = b->xp - xp;
	float by = b->yp - yp;
	
	float rd = b->R + R;
			
	if(bx * bx + by * by > rd * rd) return false;
					
	float lx = cos(rp) * R; 
	float ly = sin(rp) * R; 
						
	float dis;	
		
	float s = bx * lx + by * ly; // s = R * distance of intersection along l
			
	if(s < 0) {			
		dis = bx * bx + by * by;
		*nx = bx;
		*ny = by;
		
		*d = 0;
	} else
	if(s > R * R) {
		
		float x2 = xp + lx;
		float y2 = yp + ly;
		
		dis = (b->xp - x2) * (b->xp - x2) + (b->yp - y2) * (b->yp - y2);
		
		*nx = b->xp - x2;
		*ny = b->yp - y2;
		
		*d = R;
	} else {									
		float D = lx * by - bx * ly; // R * distance
		dis = D * D / (R * R); // squared distance
		
		*nx = ly;
		*ny = -lx;
		
		*d = s / R;
	}
			
	if(dis > b->R * b->R) return false;
			
	*sx = cos(rp);
	*sy = sin(rp);
	
	return true;
	
}

void Line::point(float percent, float *x, float *y) {
	*x = xp + cos(rp) * percent * R;
	*y = yp + sin(rp) * percent * R;
}

void Line::draw() {
				
	//line(page, int(xp), int(yp),
	//	int(xp + cos(rp) * R),
	//	int(yp + sin(rp) * R), makecol(255, 0, 0));
	
}