from pyspades.server import set_hp
from pyspades.constants import FALL_KILL, WEAPON_KILL
from twisted.internet.reactor import callLater
from commands import name, alias, add, admin
import commands
        

@alias('hc')
@admin
@name('healthcap')
def hp_cap_set(self, value):
    value = int(value)
    self.protocol.hp = value
    return 'Max HP set to %i' % value
commands.add(hp_cap_set)

def inc_hp(self):
    self.hp = self.protocol.hp
    set_hp.hp = self.protocol.hp
    set_hp.not_fall = False
    self.send_contained(set_hp)


def apply_script(protocol, connection, config):

    class HProtocol(protocol):

        hp = 255 # 255 can be considered as max, everything above 255 actualy works but it is gonna fuck the client up

        
    class HPconnection(connection):

        def set_hp(self, value, hit_by = None, type = WEAPON_KILL, hit_indicator = None, grenade = None):  # stolen from server.py
            value = int(value)
            if value>255: value = 255
            self.hp -= abs(value)
            if self.hp <= 0:
                self.kill(hit_by, type, grenade)
                return
            set_hp.hp = self.hp
            set_hp.not_fall = int(type != FALL_KILL)
            if hit_by is not None:
                hit_indicator = hit_by.world_object.position.get()
            else:
                hit_indicator = (0, 0, 0)
            x, y, z = hit_indicator
            set_hp.source_x = x
            set_hp.source_y = y
            set_hp.source_z = z
            self.send_contained(set_hp)
        
        def on_hit(self, hit_amount, hit_player, type, grenade):
            swag = connection.on_hit(self, hit_amount, hit_player, type, grenade) # in order to not get bored i gotta name my variables weirdly
            if not (swag == None or swag == False) or grenade and hit_player == self and swag != False: hit_player.set_hp(hit_amount, self, type, 'i can put here whatever i want', grenade)
            return False

        def on_spawn(self, pos):
            inc_hp(self)
            return connection.on_spawn(self, pos)

        def on_refill(self):
            callLater(0.1, inc_hp, self) 
            return connection.on_refill(self)

    return HProtocol, HPconnection