"""Amulet of Lifesaving.  This is the cool stuff.

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

from wyvern.lib import Monster, HookCallback
from wyvern.lib.classes.armor import Amulet
from wyvern.world import World

class amulet_lifesaving(Amulet, HookCallback):

    def initialize(self):
        self.super__initialize()
        self.setDefaultImage("magic/amulet")
        self.setProperty('short', 'amulet')
        self.setProperty('id', 'Amulet of Lifesaving')
        self.setProperty('id-desc', "This amulet will save the wearer's life.  It only works ONCE.")

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

        self.super__setWorn(worn, agent)

        # make sure they're a monster
        if not isinstance(agent, Monster):
            return

        if worn:
            agent.addHook(self, 'deathPreHook')
            agent.addHook(self, 'deathFailedPostHook')
        else:
            agent.removeHook(self, 'deathPreHook')
            agent.removeHook(self, 'deathFailedPostHook')


    # if they're about to die, save them
    def hookEvent(self, hookname, event):

        # pre-hook
        if hookname == 'deathPreHook':
            self.agent = event.getAgent()
            event.veto ( "You die.\nBut wait!  " \
                         + "Your medallion begins to glow." \
                         + "\nYour life has been saved." )
        # post-hook
        else:
            self.forceRemoval()
            agent = self.agent
            inv = agent.getInventory()
            inv.remove(self)
            self.destroy()

            agent.message ( 'Your medallion crumbles to dust.' )

            # adjustHP doesn't go over their max
            agent.adjustHP(agent.getIntProperty('max-hp'))
            agent.adjustSP(agent.getIntProperty('max-sp'))

            agent.broadcast ( agent.toString() + \
                                   "'s life has been saved." )

#              loc = World.getRestartLocation()
#              cmd = "teleport " + loc.getMap() + " " + \
#                    str(loc.getX()) + " " + str(loc.getY())
#              agent.commandNow(cmd)

    def isIdentified(self):
        if self.hasProperty("identified"):
            return 1
        return not self.hasProperty("id")