import math

import BigWorld
from Avatar import PlayerAvatar
from gui.Scaleform.daapi.view.battle.classic.stats_exchange import FragsCollectableStats
from Vehicle import Vehicle

import xvm_battle.python.battle as battle
import xvm_main.python.config as config
from xfw import *
from xfw_actionscript.python import *
from xvm_main.python.logger import *

timeAIM = None
vehicle = None


@registerEvent(FragsCollectableStats, 'addVehicleStatusUpdate')
def aiming_addVehicleStatusUpdate(self, vInfoVO):
    if config.get('sight/enabled', True) and battle.isBattleTypeSupported:
        if (not vInfoVO.isAlive()) and (vehicle is not None) and (vehicle.id == vInfoVO.vehicleID):
            global timeAIM
            timeAIM = None
            as_event('ON_AIMING')


@registerEvent(Vehicle, 'onEnterWorld')
def aiming_onEnterWorld(self, prereqs):
    if self.isPlayerVehicle and config.get('sight/enabled', True):
        global vehicle, timeAIM
        timeAIM = None
        if battle.isBattleTypeSupported:
            vehicle = self
        else:
            vehicle = None


@registerEvent(PlayerAvatar, 'getOwnVehicleShotDispersionAngle')
def aiming_getOwnVehicleShotDispersionAngle(self, turretRotationSpeed, withShot=0):
    global timeAIM
    if config.get('sight/enabled', True) and battle.isBattleTypeSupported and self.isVehicleAlive:
        aimingStartTime, aimingFactor, shotDispMultiplierFactor, _1, _2, _3, aimingTime = self._PlayerAvatar__aimingInfo
        prevTimeAIM = timeAIM
        # aimingStartTime = aimingInfo[0]
        # aimingFactor = aimingInfo[1]
        # shotDispMultiplierFactor = aimingInfo[2]
        # unShotDispersionFactorsTurretRotation = aimingInfo[3]
        # chassisShotDispersionFactorsMovement = aimingInfo[4]
        # chassisShotDispersionFactorsRotation = aimingInfo[5]
        # aimingTime = aimingInfo[6]
        aimingTimeAll = math.log(aimingFactor / shotDispMultiplierFactor) * aimingTime
        timeAIM = aimingTimeAll + aimingStartTime - BigWorld.time()
        timeAIM = 0.0 if timeAIM < 0.01 else timeAIM
        try:
            if not (-0.01 < (prevTimeAIM - timeAIM) < 0.01):
                as_event('ON_AIMING')
        except Exception:
            as_event('ON_AIMING')


@xvm.export('sight.timeAIM', deterministic=False)
def sight_timeAIM():
    return timeAIM
