-- global vars
patrolDestination = { x=500.0, y=500.0, z=0.0 }
moveLeft = true
-- helper functions
function watchPosition(actor, pos)
	y = pos.y - actor.position.y
	x = pos.x - actor.position.x
	rotation = math.atan(y, x)
	actor.rotation = math.deg(rotation)
end

function distance(a, b)
	return math.sqrt((math.abs(a.x - b.x)^2) + (math.abs(a.y - b.y)^2))
end

function moveTo(actor, pos)
	watchPosition(actor, pos)
	if distance(actor.position, pos) < 50 then 
		return true
	end
	actor:moveForward()
	return false
end

-- Behaviour Functions called on AI

-- These functions are ai behaviour functions called in the game
-- The AI will be spawned in idle mode, so if you want to put the bot into patrol mode 
-- It's on you to do that in this function.
function idle(actor, target)
	if target ~= nil then
	--	print("target is at " .. target.position.x)
	--	watchPosition(actor, target.position)
		ai.state = AIState.Patrol
		actor.rotation = 180
	end
	actor:shoot()
	--print("actor is idling at " .. actor.position.x)
end

-- It is most appropriate to put any patrolling behaviour into this function of course
function patrol(actor, target)
	if target ~= nil then
	--	print("target is at " .. target.position.x)
	end
	--if moveTo(actor, patrolDestination) == true then
	--	patrolDestination = { x=math.random(400.0, 750.0), y=math.random(400.0, 750.0), z=0.0 }
	--end
	-- performRaycast returns if true if the raycast hits the target position it also sets the getter function
	-- distFromWall, at bot creation distFromWall is and infinite float value.
	-- This performRaycast function is highly discourage due to slow down
	--if raycaster:performRaycast(actor.position, actor.rotation, target.position) == true then
		--ai.state = AIState.Alert
	--end
	if raycaster:bresenhamRaycast(actor.position, actor.rotation, target.position) == true then
		--target hit!
		ai.state = AIState.Alert
	end
	if raycaster:distFromWall() < 3 then
		upOrDown = math.random(2)
		if moveLeft == true then
			if upOrDown == 1 then
				actor.rotation = 180
			else
				actor.rotation = 270
			end
			moveLeft = false
		else 
			if upOrDown == 1 then
				actor.rotation = 0
			else
				actor.rotation = 90
			end
			moveLeft = true
		end
	end
	actor:moveForward()
end

-- the ai has found the player, this is what function is called
function alert(actor, target)
	if target ~= nil then
	--	print("target is at " .. target.position.x)
		watchPosition(actor, target.position)
	end
	--print("actor is alert at " .. actor.position.x)
	if distance(actor.position, target.position) > 300 then
		actor:moveForward()
	end
	actor:shoot()
end
