"""Makes the wearer invisible.

Copyright 1999 Cabochon Technologies, Inc.
Author: Steve Yegge
"""

from wyvern.lib import Timed, Monster, Kernel
from wyvern.lib.classes.armor import Cloak
from wyvern.lib.properties import Invisible

class cloak_of_invisibility(Cloak, Timed):

    def initialize(self):
        self.super__initialize()
        self.setProperty('short', 'Cloak of Invisibility')
        self.setImage('armor/cloak/cloak_of_invisibility')
        self.setIntProperty('ac', 7)
        self.setIntProperty('invisible', 1)
        self.setIntProperty('max-hp', 150)
        self.setIntProperty('hp', 150)

        self.active = 0
        self.timer = None

    # sadly, this code is all copied from the ring of invis,
    # since there's no way I know of to handle it via multiple
    # inheritance or delegation.  It does have the minor difference
    # that cloaks of invisibility are automatically identified.

    def setWorn(self, worn, agent):
        # no change -> do nothing
        if self.isWorn() == worn:
            return

        self.super__setWorn(worn, agent)

        if worn:
            self.putOnCloak(agent)
        else:
            self.removeCloak(agent)

    # puts on the cloak and starts draining mana
    def putOnCloak(self, agent):
        if not isinstance(agent, Monster):
            return

        if agent.getSP() > 0:
            self.becomeInvisible(agent)

        # paranoia - don't set multiple timers
        if self.timer:
            return

        self.timer = Kernel.setRepeatingTimer(10*1000, self)
        self.agent = agent

    # removes and stops draining mana
    def removeCloak(self, agent):
        if not isinstance(agent, Monster):
            return

        if self.active == 1:
            self.becomeVisible(agent)

        Kernel.killTimer(self.timer)
        self.timer = None

    def timerExpired(self):
        agent = self.agent
        agent.adjustSP(-1)

        # if out of mana, turn off the invisibility
        if agent.getSP() == 0:
            if self.active:
                self.becomeVisible(agent)
        else:
            # we want to become invisible, if necessary, since
            # they may have recovered enough mana since our last
            # timer to become invisible again.  This has a side-
            # effect that if you're wearing a cloak and a ring
            # of invis, and you run out of sp, and take off the
            # cloak, and then get some sp back, the ring won't
            # make you invis until this timer goes off (up to 10
            # seconds later).  Oh well.
            if not self.active:
                self.becomeInvisible(agent)

    def becomeInvisible(self, agent):
        Invisible().increase(agent)
        self.active = 1

    def becomeVisible(self, agent):
        Invisible().decrease(agent)
        self.active = 0