from core.tuning.skill import SkillTuning
from siege import game
from siege.network import NetworkManager
from siege.world import World


class Invisible(object):
    NAME = "Invisible"
    ICON = SkillTuning.INVISIBLE.ICON
    FRIENDLY_ALPHA = 128
    ENEMY_ALPHA = 0

    def __init__(self, owner, level, duration):
        self.ownerId = owner.id
        owner.combat.isTargetable.set(False)
        if owner.has('physics') and not NetworkManager.isStandalone():
            player = World.get().getPlayer()
            self.alpha = Invisible.FRIENDLY_ALPHA if not player or player.entity.combat.team == owner.combat.team else Invisible.ENEMY_ALPHA
            owner.physics.onTimeStep.listen(self.handleUpdate)
        game.events['deal_damage'].listen(self.handleDealDamage)

    def onRemove(self, owner):
        owner.combat.isTargetable.set(True)
        if owner.render.alpha == self.alpha:
            owner.render.alpha = 255
        if owner.has('physics'):
            owner.physics.onTimeStep.remove(self.handleUpdate)
        game.events['deal_damage'].remove(self.handleDealDamage)

    def handleUpdate(self, physics, timestepTime):
        physics.getParent().render.alpha = self.alpha

    def handleDealDamage(self, player, results, attacker, target, data, isCritical, damage):
        if self.ownerId == attacker.id:
            attacker.effects.remove(Invisible.NAME)
        elif self.ownerId == target.id:
            target.effects.remove(Invisible.NAME)

    def isPositive(self):
        return True

    @staticmethod
    def register():
        game.effects.register(Invisible.NAME, Invisible)
