#include "main.h"

#define TICKRATE 200

float targetangle = -1;

float simulateShot(spaceship self, spaceship enemy, vector<planet*> planetlist, screen *scr) {
	float distance1 = sqrt(pow(enemy.y - self.y, 2) + pow(enemy.x - self.x, 2));
	float time1 = distance1 / (BULLETSPEED);
	float x = enemy.x + enemy.speedx * time1;
	float y = enemy.y + enemy.speedy * time1;
	
	float sigma = atan2(y  - self.y, x - self.x) * 180 / M_PI;
	return sigma + 90;
}


void AImove(spaceship &self, spaceship &enemy, vector<planet*> planetlist, screen *scr) {
	GLuint tmp = SDL_GetTicks();
	if (tmp - self.ticks1 > 10) {
		targetangle = simulateShot(self, enemy, planetlist, scr);
		self.angle = targetangle;
		float distance = sqrt(pow(self.x - enemy.x, 2) +
				      pow(self.y - enemy.y, 2));
		if (distance > 120)
			self.setAcceleration(ACCELERATION);
		else 
			self.setAcceleration(0);
		
		for (unsigned int i = 0; i < planetlist.size(); i++) {
			if (planetlist[i]->mass == 0)
				continue;
			distance = sqrt(pow(planetlist[i]->x - self.x, 2) +
					pow(planetlist[i]->y - self.y, 2)) -
					planetlist[i]->width/2 - self.width/2;
			float theta = atan2(planetlist[i]->y - self.y, 
					    planetlist[i]->x - self.x) * 180/M_PI + 90;
			if (distance < planetlist[i]->width/2) {
				while (self.angle > 360) 
					self.angle -= 360;
				while (self.angle < 0)
					self.angle += 360;
				while (theta > 360)
					theta -=360;
				while(theta < 0)
					theta += 360;
				theta = theta - self.angle;
				while (theta> 360)
					theta -= 360;
				while (theta < 0)
					theta+=360;
				if (theta < 180) {
					self.angle -= (90 - distance/2);	
				} else {
					self.angle += (90 - distance/2);
				}
				self.setAcceleration(ACCELERATION);
			}
		}
		self.ticks1 = tmp;
	}
	if (tmp - self.ticks2 > 300) {

		self.shoot();
		
		
		self.ticks2 = tmp;
	}

	
}
	
	




