from Avatar import PlayerAvatar
from xfw import registerEvent, as_event, as_callback, log
from gui.shared.utils.TimeInterval import TimeInterval
from gui.Scaleform.daapi.view.battle.shared.consumables_panel import ConsumablesPanel
from gui.Scaleform.daapi.view.battle.shared.damage_panel import DamagePanel

ENGINE = 'engine'
AMMOBAY = 'ammoBay'
GUN = 'gun'
TURRET = 'turretRotator'
TRACKS = 'tracks'
LEFTTRACK = 'leftTrack'
RIGHTTRACK = 'rightTrack'
SURVEYING = 'surveyingDevice'
RADIO = 'radio'
FUELTANK = 'fuelTank'

DEVICES = (
    ENGINE, AMMOBAY, GUN, TURRET, LEFTTRACK, RIGHTTRACK, SURVEYING, RADIO, FUELTANK
)

EVENTS = {
    ENGINE: 'ON_ENGINE_UPDATE',
    AMMOBAY: 'ON_AMMOBAY_UPDATE',
    GUN: 'ON_GUN_UPDATE',
    TURRET: 'ON_TURRET_UPDATE',
    LEFTTRACK: 'ON_TRACKS_UPDATE',
    RIGHTTRACK: 'ON_TRACKS_UPDATE',
    SURVEYING: 'ON_SURVEYING_UPDATE',
    RADIO: 'ON_RADIO_UPDATE',
    FUELTANK: 'ON_FUELTANK_UPDATE'
}

STATES = {
    ENGINE: 'normal',
    AMMOBAY: 'normal',
    GUN: 'normal',
    TURRET: 'normal',
    LEFTTRACK: 'normal',
    RIGHTTRACK: 'normal',
    SURVEYING: 'normal',
    RADIO: 'normal',
    FUELTANK: 'normal'
}

consumablesPanel = None

def resetAll():
    global STATES, EVENTS
    for device in DEVICES:
        if device in RepairTimers.TIMERS:
            RepairTimers.stopTimer(device)
        STATES[device] = 'normal'
        as_event(EVENTS[device])

#TIMERS

class RepairTimers(object):

    def __init__(self):
        self.TIMERS = {
            ENGINE: {
                'timer': None,
                'duration': None
            },
            GUN: {
                'timer': None,
                'duration': None
            },
            TURRET: {
                'timer': None,
                'duration': None
            },
            LEFTTRACK: {
                'timer': None,
                'duration': None
            },
            RIGHTTRACK: {
                'timer': None,
                'duration': None
            },
            SURVEYING: {
                'timer': None,
                'duration': None
            }
        }

    def startTimer(self, device, duration):
        self.TIMERS[device]['duration'] = duration
        if self.TIMERS[device]['timer'] is not None:
            return
        self.TIMERS[device]['timer'] = TimeInterval(0.1, self, '{}OnTimer'.format(device))
        self.TIMERS[device]['timer'].start()
        as_event(EVENTS[device])

    def stopTimer(self, device):
        if self.TIMERS[device]['timer'] is None:
            return
        self.TIMERS[device]['timer'].stop()
        self.TIMERS[device]['timer'] = None
        self.TIMERS[device]['duration'] = None

    def onTimer(self, device):
        self.TIMERS[device]['duration'] -= 0.1
        as_event(EVENTS[device])

    def engineOnTimer(self):
        self.onTimer(ENGINE)

    def gunOnTimer(self):
        self.onTimer(GUN)

    def turretRotatorOnTimer(self):
        self.onTimer(TURRET)

    def leftTrackOnTimer(self):
        self.onTimer(LEFTTRACK)
        if self.TIMERS[RIGHTTRACK]['timer'] is not None and self.TIMERS[LEFTTRACK]['duration'] > self.TIMERS[RIGHTTRACK]['duration']:
            self.stopTimer(RIGHTTRACK)

    def rightTrackOnTimer(self):
        self.onTimer(RIGHTTRACK)
        if self.TIMERS[LEFTTRACK]['timer'] is not None and self.TIMERS[RIGHTTRACK]['duration'] > self.TIMERS[LEFTTRACK]['duration']:
            self.stopTimer(LEFTTRACK)

    def surveyingDeviceOnTimer(self):
        self.onTimer(SURVEYING)

    def getLastTrack(self):
        return LEFTTRACK if self.TIMERS[LEFTTRACK]['duration'] > self.TIMERS[RIGHTTRACK]['duration'] else RIGHTTRACK

RepairTimers = RepairTimers()

#EXPORTS TIMERS

@xvm.export('repairTimeEngine', deterministic=False)
def repairTimeEngine():
    return RepairTimers.TIMERS[ENGINE]['duration']

@xvm.export('repairTimeGun', deterministic=False)
def repairTimeGun():
    return RepairTimers.TIMERS[GUN]['duration']

@xvm.export('repairTimeTurret', deterministic=False)
def repairTimeTurret():
    return RepairTimers.TIMERS[TURRET]['duration']

@xvm.export('repairTimeTracks', deterministic=False)
def repairTimeTracks():
    return RepairTimers.TIMERS[RepairTimers.getLastTrack()]['duration']

@xvm.export('repairTimeSurveying', deterministic=False)
def repairTimeSurveying():
    return RepairTimers.TIMERS[SURVEYING]['duration']

#REPAIR

def repairHandler(data):
    repair_kit = 1275
    device = data['name']
    if device == TRACKS:
        device = RepairTimers.getLastTrack()
    consumablesPanel._ConsumablesPanel__handleEquipmentPressed(repair_kit, device)
    log('data: {}, device: {}'.format(data, device))

as_callback(ENGINE, repairHandler)
as_callback(AMMOBAY, repairHandler)
as_callback(GUN, repairHandler)
as_callback(TURRET, repairHandler)
as_callback(TRACKS, repairHandler)
as_callback(SURVEYING, repairHandler)
as_callback(RADIO, repairHandler)
as_callback(FUELTANK, repairHandler)

def getDeviceState(device):
    return STATES[device].replace('repaired', 'normal')

#EXPORTS REPAIRS

@xvm.export('repairEngineState', deterministic=False)
def repairEngineState():
    return getDeviceState(ENGINE)

@xvm.export('repairAmmoBayState', deterministic=False)
def repairAmmoBayState():
    return getDeviceState(AMMOBAY)

@xvm.export('repairGunState', deterministic=False)
def repairGunState():
    return getDeviceState(GUN)

@xvm.export('repairTurretState', deterministic=False)
def repairTurretState():
    return getDeviceState(TURRET)

@xvm.export('repairTracksState', deterministic=False)
def repairTracksState():
    return getDeviceState(RepairTimers.getLastTrack())

@xvm.export('repairSurveyingState', deterministic=False)
def repairSurveyingState():
    return getDeviceState(SURVEYING)

@xvm.export('repairRadioState', deterministic=False)
def repairRadioState():
    return getDeviceState(RADIO)

@xvm.export('repairFuelTankState', deterministic=False)
def repairFuelTankState():
    return getDeviceState(FUELTANK)

#REGISTERS

@registerEvent(DamagePanel, '_updateRepairingDevice')
def _updateRepairingDevice(self, value):
    device = value[0]
    if device in RepairTimers.TIMERS:
        RepairTimers.startTimer(device, float(value[2]))

@registerEvent(DamagePanel, '_updateDeviceState')
def _updateDeviceState(self, value):
    global STATES, EVENTS
    device = value[0]
    state = value[2]
    if 'destroyed' != state and device in RepairTimers.TIMERS:
        RepairTimers.stopTimer(device)
    if device in DEVICES:
        STATES[device] = state
        as_event(EVENTS[device])

@registerEvent(DamagePanel, '_updateDestroyed')
def _updateDestroyed(self, _ = None):
    resetAll()

@registerEvent(ConsumablesPanel, '_ConsumablesPanel__onEquipmentAdded')
def __onEquipmentAdded(self, intCD, entityName = None):
    global consumablesPanel
    consumablesPanel = self

@registerEvent(ConsumablesPanel, '_ConsumablesPanel__onEquipmentUpdated')
def __onEquipmentUpdated(self, intCD, entityName = None):
    global consumablesPanel
    consumablesPanel = self

@registerEvent(PlayerAvatar, '_PlayerAvatar__destroyGUI')
def _PlayerAvatar__destroyGUI(self):
    resetAll()
