from unity import *

import ComponentUtil
import SteeringControl
import PursuitRealism
import WeaponController
import TurretAim
import TurretBase

import ClevernessUtil

class TurretAttackTarget(SteeringControl):
	def __init__(self, target):
		self.controller = False
		self.target = target
		# TODO Maybe pass in the target priority?
		self.steerInit("Turret Attack "+target.name, 30)

		self.pursuit = PursuitRealism()
		self.pursuit.target = target.gameObject
		self.pursuit.leadImagination = Random.Range(-1000.0, 1000.0) / 1000.0
		self.pursuit.reactiveness = 1.0

		self.firing = 0

	def init(self):
		self.turretAim = ComponentUtil.findInLineage[TurretAim](self.gameObject)
		self.turretBase = Beaker[TurretBase].family(self.gameObject)
		self.weaponController = ComponentUtil.findInLineage[WeaponController](self.gameObject)

	def step(self):
		# for key, item in self.__dict__.iteritems():
			# Debug.Log("%s : %s" % (key, item))

		if self.target == None:
			self.controller.pop(self)

		if not self.turretBase.component.pointWithinCoverage(self.target.transform.position):
			self.controller.pop(self)

		transform = self.gameObject.transform
		targetPosition = self.target.transform.position
		interceptPoint = targetPosition
		toTarget = targetPosition - transform.position
		targetDistance = toTarget.magnitude

		projectedTargetPosition = targetPosition

		if targetDistance < 900:
			projectedTargetPosition = ClevernessUtil.predictInterceptPoint(transform.position, \
					self.weaponController.currentSystem().ordinanceVelocity, self.target.gameObject)

		interceptPoint = self.pursuit.step(projectedTargetPosition, targetDistance)

		toProjectedPosition = projectedTargetPosition - transform.position
		projectedDistance  = toProjectedPosition.magnitude

		if projectedDistance > self.weaponController.activeRange() * 1.1:
			self.controller.pop(self)

		self.firing -= Time.deltaTime

		if self.firing > 0:
			self.weaponController.fireActiveWeapon();

		aoa = Vector3.Dot(transform.forward, toProjectedPosition.normalized)

		# Debug.LogError("%f Firing.. %f %f" % (self.firing, aoa, self.weaponController.currentSystem().effectiveAoa))

		if aoa >= self.weaponController.currentSystem().effectiveAoa:
			Debug.DrawLine(transform.position, interceptPoint, Color(0, 1, 0, (aoa / 2) + .5));
			# Debug.Log("Range %f" % self.weaponController.activeRange())
			# if Mathf.Clamp01(projectedDistance / self.weaponController.activeRange()) < Random.Range(0.0, 1000) / 1000.0:
				# self.weaponController.fireActiveWeapon()
			if self.firing <= Random.Range(-10, -20) / 10.0:
				self.firing = Random.Range(10, 100) / 100.0

		self.turretAim.turnTowardsPoint(interceptPoint)

