import es
import gamethread
import random
import playerlib

import wcs
from wcs import wcs

raceName = "Orcish Horde"
race     = wcs.Race(raceName)

""" Load the strings into the variable text """
text     = race.loadStrings()

""" ############################### """
""" ### Begin the configuration ### """
""" ############################### """

config   = race.config()

config.addComment('********************')
config.addComment('Critical Strike')
config.addComment('  This skill gives a chance of dealing additional damage')
config.addComment('  to others.')
config.addComment('********************')
config.addComment()
critStrikeMaxLevel      = config.addVar('critStrikeMaxLevel',      6, 'The maximum level for the Critical Strike Skill')
critStrikeLevelInterval = config.addVar('critStrikeLevelInterval', 2, 'The intervals between the abilities to upgrade their Critical Strike skill')
critStrikeDamage        = config.addVar('critStrikeDamage',        6, 'This is the amount of additional damage gave multiplied by their level')

config.addComment()
config.addComment('********************')
config.addComment('Critical Grenade')
config.addComment('  This skill deals additional damage with grenades')
config.addComment('********************')
config.addComment()
critNadeMaxLevel        = config.addVar('critNadeMaxLevel',      8, 'The maximum level for the Critical Grenade skill')
critNadeLevelInterval   = config.addVar('critNadeLevelInterval', 4, 'The intervals between the abilities to upgrade their Critical Grenade skill')
critNadeDamage          = config.addVar('critNadeDamage',       10, 'The additional damage a critical grenade will damage multipplied by their level.') 

config.addComment()
config.addComment('********************')
config.addComment('Reincarnation')
config.addComment('  This skill gives a chance of respawning after death')
config.addComment('********************')
config.addComment()
reinMaxLevel           = config.addVar('reinMaxLevel',      5, 'The maximum level for the Reincarnation skill')
reinLevelInterval      = config.addVar('reinLevelInterval', 5, 'The intervals between the abilities to upgrade their Reincarnation skill')
reinPercent            = config.addVar('reinPercent',      10, 'The chance in percent that a player will respawn after death, multiplied by their level')

config.addComment()
config.addComment('********************')
config.addComment('Chain Lightning')
config.addComment('  This ultimate allows you to power up yourself to') 
config.addComment('  run in and shock all near by enemies.') 
config.addComment('  The maximum a player can charge to is a damage counter')
config.addComment('  of power 10.')
config.addComment('********************')
config.addComment()
chainMinLevel         = config.addVar('chainMinLevel',        8,  'The level required before this ultimate can be bought')
chainMaxLevel         = config.addVar('chainMaxLevel',        8,  'The maximum level for the Suicide Bomber skill')
chainLevelInterval    = config.addVar('chainLevelInterval',   4,  'The interval between the skill upgrades')
chainCoolDown         = config.addVar('chainCoolDown',        18, 'The amount of seconds after a player has used their ultimate that they cannot use it again')
chainDamage           = config.addVar('chainDamage',          2,  'The amount of damage done multiplied by their Chain level multiplied further by the damage counter (keep this betwee 1 and 4)')
chainDistance         = config.addVar('chainDistance',        50, 'The distance (in game units) multiplied by the damage counter that people will be effected. (40 game units = 1m)')

config.load(True)

""" ##################### """
""" ### END OF CONFIG ### """
""" ##################### """

race.registerSkill('Critical Strike', int(critStrikeMaxLevel), int(critStrikeLevelInterval), 'Have a chance of hitting a critical hit')

""" Critical Grenades will only work in CSS because of hegrenade. Will add support for DOD:S later. """
if wcs.dir == 'cstrike':
    race.registerSkill('Critical Grenade', int(critNadeMaxLevel), int(critNadeLevelInterval), 'You grenades will do additional damage')
    
    """ CSS is the only non-dm game which this supports... If no deathmatch option is on, then respawn them. """
    if not int(es.ServerVar('wcs_cssdm')):
        race.registerSkill('Reincarnation', int(reinMaxLevel), int(reinLevelInterval), 'Enables a random chance of respawning when you die')
        
race.registerUltimate('Chain Lightning', int(chainMinLevel), int(chainMaxLevel), int(chainLevelInterval), 'Hold down the ultimate key to release a bolt of lightning')

def player_spawn(ev):
    userid = ev['userid']
    chain  = wcs.GetLevel(userid, raceName,'Chain Lightning')
    if chain:
        wcs.Command(userid)['lightPower'] = 0
    wcs.Command(userid).CancelDelayed('lightning_%s' % userid)
	
def player_hurt(ev):
    if int(ev['attacker']) and es.getplayerteam(ev['attacker']):
        userid       = ev['userid']
        attacker     = ev['attacker']
        userteam     = ev['es_userteam']
        attackerteam = ev['es_attackerteam']
        if userteam != attackerteam and attacker:
            """ Players are on opposite teams, so do the critical strikes... """
            critStrike = wcs.GetLevel(attacker, raceName, 'Critical Strike')
            critNade   = wcs.GetLevel(attacker, raceName, 'Critical Grenade')
            if ev['weapon'] == "hegrenade" and critNade:
                """ If the weapon was a hegrenade and the players critical nade level is at least level one... """
                damage = critNade * int(critNadeDamage)
                wcs.Command(userid).Damage(damage, 32, attacker)
                tokens             = {}
                tokens['victim']   = ev['es_username']
                tokens['attacker'] = ev['es_attackername']
                tokens['damage']   = damage
                es.tell(userid,   '#multi', text('critical nade victim',   tokens, playerlib.getPlayer(userid).get("lang")   ) )
                es.tell(attacker, '#multi', text('critical nade attacker', tokens, playerlib.getPlayer(attacker).get("lang") ) )
                wcs.effect.Misc1(userid, 4)
            elif critStrike:
                """ If the weapon was not an hegrenade or the player doesn't have a level in critNade, run this method. """
                chance = random.randint(1,20)
                if chance <= critStrike:
                    damage = critStrike * int(critStrikeDamage)
                    wcs.Command(userid).Damage(damage, 32, attacker)
                    tokens             = {}
                    tokens['victim']   = ev['es_username']
                    tokens['attacker'] = ev['es_attackername']
                    tokens['damage']   = damage
                    es.tell(userid,   '#multi', text('critical strike victim',   tokens, playerlib.getPlayer(userid).get("lang")   ) )
                    es.tell(attacker, '#multi', text('critical strike attacker', tokens, playerlib.getPlayer(attacker).get("lang") ) )
                    wcs.effect.Beam2(attacker, userid, 3, 255, 0, 0)
                    
def player_death(ev):
    userid = ev['userid']
    rein   = wcs.GetLevel(userid, raceName, 'Reincarnation')
    if rein:
        rand = random.randint(1,100) 
        if rand <= rein * int(reinPercent): 
            wcs.Command(userid).Delayed(1, spawnUserid, userid)
            
def spawnUserid(userid):
    if len(filter(lambda x: not es.getplayerprop(x, 'CBasePlayer.pl.deadflag') and es.getplayerteam(x) == es.getplayerteam(userid), es.getUseridList() ) ):
        """ If a team-mate is alive... """
        wcs.Command(userid).Spawn()
        wcs.effect.Smoke(userid)
        es.tell(userid, '#multi', text('reincarnation', lang=playerlib.getPlayer(userid).get("lang") ) )
		
def player_ultimate_on(ev):
    userid = ev['userid']
    chain  = wcs.GetLevel(userid, raceName, 'Chain Lightning')
    if chain:
        wcs.Command(userid)['lightPower'] = 0
        addPower(userid)
		
def addPower(userid):
    power = wcs.Command(userid).ReturnDict('lightPower')
    if power < 10:
        wcs.Command(userid)['lightPower'] += 1
        wcs.Command(userid).HudHint("%s\n%s" % (text('power', lang=playerlib.getPlayer(userid).get("lang") ), '|' * (power + 1) ) )
        es.emitsound('player', userid, 'buttons/button19.wav', 0.5, 0.5)
    else:
        wcs.Command(userid).HudHint("%s\n%s" % (text('power', lang=playerlib.getPlayer(userid).get("lang") ), text('maxed', lang=playerlib.getPlayer(userid).get("lang") ) ) )
    wcs.Command(userid).Delayed(0.5, addPower, userid, True, 'lightning_%s' % userid)
	
def player_ultimate_off(ev):
    userid  = ev['userid']
    chain   = wcs.GetLevel(userid, raceName, 'Chain Lightning')
    command = wcs.Command(userid)
    wcs.Command(userid).CancelDelayed('lightning_%s' % userid)
    if chain:
        damage = command['lightPower']
        if damage:
            command.SetCoolDown('Chain Lightning', int(chainCoolDown) )
            es.emitsound('player', userid, 'ambient/energy/%s.wav' % random.choice(['spark4', 'spark5', 'spark6'] if damage <= 5 else ['zap1', 'zap2', 'zap3']), 0.5, 0.5)
            command.Near(damage * int(chainDistance), damagePlayer, ('#t' if ev['es_userteam'] == '3' else '#ct') )
        command['lightPower'] = 0
		
def damagePlayer(userid, attacker):
    damage = wcs.Command(attacker).ReturnDict('lightPower') * int(chainDamage) * wcs.GetLevel(attacker, raceName, 'Chain Lightning')
    wcs.effect.Beam1(userid, attacker, 5, 0, 0, 255)
    wcs.Command(userid).Damage(damage, 32, attacker)
    tokens             = {}
    tokens['victim']   = es.getplayername(userid)
    tokens['attacker'] = es.getplayername(attacker)
    tokens['damage']   = damage
    es.tell(attacker, '#multi', text('chain lightning attacker', tokens, playerlib.getPlayer(attacker).get("lang") ) )
    es.tell(userid, '#multi', text('chain lightning victim',     tokens, playerlib.getPlayer(userid).get("lang")   ) )
