
import BigWorld
from xfw import *
from gui.Scaleform.daapi.view.battle.shared.stats_exchage import BattleStatisticsDataController

from helpers import dependency
from skeletons.gui.battle_session import IBattleSessionProvider
from gui.battle_control.arena_info import vos_collections

try:
	def getLeftList():
		return playerlist.showLeftList()
		
	class ListManager():
		def __init__(self):
			self.reloadDict={}
			self.leftList=[]
			self.callback=None
		
		def start(self):
			if self.callback is None:
				self.repeat()
				
		def repeat(self):
			as_event('ON_RELOAD_REFRESH')
			if len(self.reloadDict)>0:
				self.callback=BigWorld.callback(0.1,self.repeat)
			else:
				self.callback=None
				
		def stop(self):
			if self.callback is not None:
				BigWorld.cancelCallback(self.callback)
				self.callback=None
				
		def add(self):
			sessionProvider = dependency.instance(IBattleSessionProvider)
			self.leftList=vos_collections.AllyItemsCollection(vos_collections.VehicleInfoSortKey).ids(sessionProvider.getArenaDP())
				
		def update(self,name,list):
			if name=='leftList':
				self.leftList=list
				
		def showLeftList(self):
			return self.showList(self.leftList)
			
			
		def showList(self,list):
			res=""
			now=BigWorld.time()
			for i in range(0,len(list)):
				#vo1=g_sessionProvider.getArenaDP().getVehicleInfo(list[i])
				if list[i] in self.reloadDict:
					reload=self.reloadDict[list[i]]
					remain=reload['reloadTime']-(now-reload['time'])
					if remain<0:
						self.reloadDict.pop(list[i])
					elif reload['reloadTime']>6:
						res=res+'{0:.1f}'.format(remain)
				res=res+"\n"
			return res
			
		def addRecord(self, attackerID, timeoffset):
			#err("###shot:"+str(attackerID))
			player=BigWorld.player()
			attacker = player.arena.vehicles.get(attackerID)
			if attacker is None:
				return
			vehicleType = attacker['vehicleType']
			
			attackertime = BigWorld.time()
			loader_skill = 126.5
			other_bonus = 1.0
			for item in vehicleType.optionalDevices:
				if item is not None and 'improvedVentilation' in item.name:
					loader_skill = 132.0
				if item is not None and 'TankRammer' in item.name:
					other_bonus *= 0.9
			isReload = vehicleType.gun['reloadTime'] * 0.875 / (0.00375 * loader_skill + 0.5) * other_bonus
			attackerReload = '{0:.1f}'.format(isReload)
			self.reloadDict[attackerID]={
				'time':attackertime+timeoffset,
				'reloadTime':isReload
			}
			self.start()
	playerlist=ListManager()

	@registerEvent(BattleStatisticsDataController, 'as_addVehiclesInfoS')
	def as_addVehiclesInfoS(self, data):
		if 'leftItemsIDs' in data:
			playerlist.update('leftList',data['leftItemsIDs'])

	@registerEvent(BattleStatisticsDataController, 'as_updateVehiclesInfoS')
	def as_updateVehiclesInfoS(self, data):
		if 'leftItemsIDs' in data:
			playerlist.update('leftList',data['leftItemsIDs'])
			
	@registerEvent(BattleStatisticsDataController, 'as_setVehiclesDataS')
	def as_setVehiclesDataS(self, data):
		playerlist.add()
		if 'leftItemsIDs' in data:
			playerlist.update('leftList',data['leftItemsIDs'])
			
	@registerEvent(BattleStatisticsDataController, 'as_updateVehicleStatusS')
	def as_updateVehicleStatusS(self, data):
		if 'leftItemsIDs' in data:
			playerlist.update('leftList',data['leftItemsIDs'])
			
	@registerEvent(BattleStatisticsDataController, 'as_updatePlayerStatusS')
	def as_updatePlayerStatusS(self, data):
		if 'leftItemsIDs' in data:
			playerlist.update('leftList',data['leftItemsIDs'])
				
	from Avatar import PlayerAvatar
	from Vehicle import Vehicle
	@registerEvent(Vehicle, 'showDamageFromShot')
	def new_Vehicle_showDamageFromShot(self, attackerID, center, effectsIndex, damageFactor):
		playerlist.addRecord(attackerID,-3)

	@registerEvent(Vehicle, 'showDamageFromExplosion')
	def new_Vehicle_showDamageFromExplosion(self, attackerID, center, effectsIndex, damageFactor):
		playerlist.addRecord(attackerID,-3)

	@registerEvent(Vehicle, 'onHealthChanged')
	def new_Vehicle_onHealthChanged(self, newHealth, attackerID, attackReasonID):
		playerlist.addRecord(attackerID,-3)

	@registerEvent(PlayerAvatar, 'showShotResults')
	def newShotResult(self, results):
		for r in results:
			vehicleID = r & 4294967295L
			playerlist.addRecord(vehicleID,-3)

	@registerEvent(PlayerAvatar, 'showTracer')
	def newShowTracer(self, shooterID, shotID, isRicochet, effectsIndex, refStartPoint, velocity, gravity, maxShotDist):
		playerlist.addRecord(shooterID,0)

except Exception as ex:
	err(ex)
	pass