import BigWorld
from Avatar import PlayerAvatar
from xfw import *

import math
import Math
import sys

class AimManager():
	def __init__(self):
		self.aimFactorNow=0.0
		self.aimTimeAll=0.0
		self.aimTimeRemain=0.0
		self.realDistance=0
		self.offset=0.0
		self.flyTime=0.0
		self.callback=None
		
	def repeat(self):
		self.refresh()
		as_event('ON_AIM_CHANGE')
		self.callback=BigWorld.callback(0.1,self.repeat)
			
	def stop(self):
		if self.callback is not None:
			BigWorld.cancelCallback(self.callback)
			self.callback=None
			
	def refresh(self):
		player = BigWorld.player()
		if player is None:
			self.stop()
			return
		descr=None
		try:
			descr = player.vehicleTypeDescriptor
		except:
			return
		if descr is None:
			return
		currTime = BigWorld.time()
		finishtime = math.log(self.aimingStartFactor/self.multFactor)*self.aimingTime+self.aimingStartTime
		self.aimTimeRemain=finishtime-currTime
		self.aimFactorNow = descr.gun['shotDispersionAngle']*self.aimingStartFactor * math.exp((self.aimingStartTime - currTime) / self.aimingTime)
		self.offset=self.aimFactorNow*self.realDistance
		if finishtime<currTime or (currTime-self.aimingStartTime<0.01 and self.aimingStartFactor<self.multFactor+0.2):
			self.aimFactorNow=descr.gun['shotDispersionAngle']*self.aimingStartFactor
			self.aimTimeAll = 0
			self.aimTimeRemain = 0
			self.stop()
			
	def updateAim(self):
		try:
			player = BigWorld.player()
			descr=None
			try:
				descr = player.vehicleTypeDescriptor
			except:
				return
			if descr is None:
				return
			self.aimingStartTime, self.aimingStartFactor, self.multFactor, gunShotDispersionFactorsTurretRotation, chassisShotDispersionFactorsMovement, chassisShotDispersionFactorsRotation, self.aimingTime = player._PlayerAvatar__aimingInfo
			
			#self.startTime=aimingStartTime
			self.aimTimeAll = math.log(self.aimingStartFactor/self.multFactor)*self.aimingTime
			self.realDistance=getAimDistance()
			self.flyTime=self.realDistance/descr.shot['speed']
			if self.callback is None:
				self.repeat()
				
		except Exception, e:
			s=sys.exc_info()
			err(str(s[2].tb_lineno)+' exAim|'+ str(e.message))

aim = AimManager()

@registerEvent(PlayerAvatar,'getOwnVehicleShotDispersionAngle')
def getOwnVehicleShotDispersionAngle(self, turretRotationSpeed, withShot = 0):
	aim.updateAim()
	as_event('ON_AIM_CHANGE')

def getAimDistance():
	x, y, z = BigWorld.player().gunRotator.markerInfo[0]
	v = BigWorld.player().getOwnVehiclePosition() - Math.Vector3(x, y, z)
	return int(v.length)
	
def aimFactorNow():
	return aim.aimFactorNow

def aimTimeAll():
	return aim.aimTimeAll

def aimTimeRemain():
	return aim.aimTimeRemain
	
def realDistance():
	return aim.realDistance
	
def offset():
	return aim.offset
	
def flyTime():
	return aim.flyTime
		