

import es
import playerlib,popuplib
from random import randrange

info = es.AddonInfo()
info.name        = "Hail Mary"
info.version     = "1.5P"
info.author      = "*XYZ*SaYnt"
info.url         = "http://addons.eventscripts.com/addons/view/hailmary"
info.basename    = "hailmary"
info.description = "allows the CTs to try to pull wires to defuse the bomb, in addition to regular defusing."


# global variables
conf = {}

###############################################################################
## User Configuration Section
###############################################################################
def config():
   #set this variable to 1 if you want the terrorists to be able to 
   #choose the wire connected to the detonator (in other words, the
   #wire that CT's have to cut to quick-defuse the bomb)
   #set this variable to 0 if you just want a simple random number
   #generator to pick the wire.
   conf['tselect'] = 1

   #multiplier for the odds when defusing without a defuse kit (pulling a wire).  The odds
   #of success become 1:(4*HM_MULTIPLIER).
   #so, if you want a CT to be able to have the same odds whether pulling or cutting, set
   #this to 1.  To make it nearly impossible for CTs to successfully pull a wire, set this
   #to 100.  By default it is 2, making the odds 1:8.

   conf['multiplier'] = 2
   
   # set the verbosity level.  If you feel like HailMary spams too much, change
   # this setting appropriately.
   #
   # 0 = never say anything at all
   # 1 = just the bare necessities - remind the CT's when the bomb is planted
   #     that they can cut a wire to defuse (1 line), and also tell info on
   #     wire correctness when a wire is cut.
   # 2 = all printouts in (1), but with two lines for the CT reminder, and
   #     a notice when a terrorist selects a wire.
   # 3 = all printouts in (2), but with notices when the bomb planter or
   #     defuser are killed.
   #
   conf['verbosity'] = 1
   
   # the prefix to place in front of chat from the hailmary addon
   conf['chatprefix'] = "[HM]"
###############################################################################























hminfo = {}
wirecolor = {1:"Красный",2:"Зеленый",3:"Голубой",4:"Желтый"}
 
 
def load():
    es.set("hailmary_version",info.version)
    es.makepublic("hailmary_version")
    
    #import the user's configs
    config()

    #create the popup menu for the CTs
    ct_menu = popuplib.create('ct_menu')
    ct_menu.addline("Продолжайте или обрежте провод:")
    ct_menu.addline("[0] Продолжать")
    ct_menu.addline("[1] Красный")
    ct_menu.addline("[2] Зеленый")
    ct_menu.addline("[3] Голубой")
    ct_menu.addline("[4] Желтый")
    ct_menu.menuselect = ct_menuselect
    
    ct_menu2 = popuplib.create('ct_menu2')
    ct_menu.addline("Продолжайте или обрежте провод:")
    ct_menu.addline("[0] Продолжать")
    ct_menu.addline("[1] Красный")
    ct_menu.addline("[2] Зеленый")
    ct_menu.addline("[3] Голубой")
    ct_menu.addline("[4] Желтый")
    ct_menu.menuselect = ct_menuselect

    #create a popup menu for the Ts
    t_menu = popuplib.create('t_menu')
    t_menu.addline("Выберите провод для детонатора:")
    t_menu.addline("[0] Случайный выбор")
    t_menu.addline("[1] Красный")
    t_menu.addline("[2] Зеленый")
    t_menu.addline("[3] Голубой")
    t_menu.addline("[4] Желтый")
    t_menu.menuselect = t_menuselect
  
    inithm()
    
    es.regsaycmd("hailmary","hailmary/hailmary","HailMary debugging")

def hailmary():
    userid = es.getcmduserid()
    killpopup()
    popuplib.send('t_menu',str(userid))

def unload():
    killpopup()
    popuplib.delete('ct_menu')
    popuplib.delete('ct_menu2')
    popuplib.delete('t_menu')


def inithm():
    hminfo['defuserid'] = '-1'
    hminfo['planterid'] = '-1'
    hminfo['defusername'] = "noname"
    hminfo['plantername'] = "noname"
    hminfo['wire'] = 0
    hminfo['exploding'] = 0
    hminfo['pullodds'] = 4*conf['multiplier']
    hminfo['action'] = 'cut'  

def round_start(ev):
    inithm()

def round_end(ev):
    killpopup()

def bomb_beginplant(ev):
    #use a random number generator to set the wire color that will successfully
    #defuse the bomb.  This is so that if the planter does not choose a wire, 
    # one is randomly chosen for him.
    hminfo['wire'] = randrange(1,4)

    # save off who is doing the planting
    hminfo['planterid']   = ev['userid']
    hminfo['plantername'] = ev['es_username']

    # send a menu to the planter, to let them choose the wire color that
    # will detonate  
    if conf['tselect']:
        popuplib.send('t_menu',ev['userid'])
        
    

def bomb_abortplant(ev):
    no_more_t_menu()


def no_more_t_menu():
    hminfo['planterid'] = "noname"
    hminfo['plantername'] = '-1'
    killpopup()


def no_more_ct_menu():
    hminfo['defuserid'] = "noname"
    hminfo['defusername'] = '-1'
    killpopup()
    
def bomb_planted(ev):
    #take down the popup; the T has lost his chance to choose wires.
    no_more_t_menu()

    #remind the CTs that they can defuse by cutting or pulling wires.
    message("CTs: Вы можете быстро обезвредить бомбу, обрезав провод.")
    message("Если вы обрежете не тот провод, бомба сразу же взорвется.")
    
    #message("Обман: вы должны обрезать %s провод" % wirecolor[hminfo['wire']])


def bomb_begindefuse(ev):
    bombentity = hminfo['bombentity'] = es.getentityindex("planted_c4")
    bombpos    = es.getindexprop(bombentity,"CPlantedC4.baseclass.baseclass.m_vecOrigin")

    #save the player ID that is doing the defusing.
    hminfo['defuserid']   = ev['userid']
    hminfo['defusername'] = ev['es_username']
  
    #here, pop the menu that allows the player to choose whether or not 
    #to cut a wire.  If they have a kit, they can cut the wire.  If they do
    #not, they have to pull the wire, which gives a 50/50 chance of setting off
    #the bomb even if it is the right wire.
    hminfo['haskit'] = int(ev['haskit'])
    if ev['haskit'] == '0':
         popuplib.send('ct_menu2',int(ev['userid']))
         hminfo['action'] = 'pulled'
    else:
         popuplib.send('ct_menu',int(ev['userid']))
         hminfo['action'] = 'cut'




def bomb_abortdefuse(ev):
    isdead = es.getplayerprop(ev['es_username'],"CCSPlayer.baseclass.pl.deadflag")  
    if isdead == '0':
        if hminfo['exploding'] == '0':
            message("%s только что престал обезвреживать бомбу." % ev['es_username'],3)

    #take down the menu.
    no_more_ct_menu()


def player_death(ev):
    if ev['userid'] == hminfo['defuserid']:
        no_more_ct_menu()
        message("Тот, кто разряжал бомбу %s, был убит!" % ev['es_username'],2)
         
  
    if ev['userid'] == hminfo['planterid']:
        no_more_t_menu()
        message("Тот, кто устанавливал бомбу %s, был убит!" % ev['es_username'],2)  

 

def t_menuselect(userid,choice,popupid):
    if choice >= 1 and choice <= 4:
        hminfo['wire'] = choice
        message("%s выбрал провод для детонатора."%hminfo['plantername'],3)
    killpopup()
    
    

def message(s,verb=0):
    if conf['verbosity'] > verb:
        es.msg("#multi","#green %s #default %s" % (conf['chatprefix'],s))
    
    
def ct_menuselect(userid,choice,popupid):
    if choice >= 1 and choice <= 4:
        do_cutwire(choice)


def do_cutwire(cutwire):
  if hminfo['defuserid'] > -1:   
      isdead = es.getplayerprop(hminfo['defuserid'],"CCSPlayer.baseclass.pl.deadflag")
      if isdead != '0': 
          message("%s %s  %s провод" % (hminfo['defusername'],hminfo['action'],wirecolor[cutwire]),0)
          
          #if the wire that was cut and the detonator wire match, then the
          #bomb is instantly defused, UNLESS the defuser does not have a kit.
          #In that case, the defuser pulled the wire, which means that there
          #is a 50-50 chance it will still detonate, even though he chose the
          #correct wire.        
          if hminfo['wire'] == cutwire:
              dice = 1
              describe =  "a wire cut (1:4 odds)"
              if hminfo['haskit'] == 0:
                  dice = randrange(1,conf['multiplier'])                              
                  describe = "a gutsy wire pull (1:%d odds)" % hminfo['pullodds']
             
              if dice == 1:
                  #defuse the bomb immediately
                  message("Бомбу разрядил%s  %s" % (describe,hminfo['defusername']))
                  es.setindexprop(hminfo['bombentity'],"CPlantedC4.m_flDefuseCountDown",'1.0')
              else:       
                  #explode the bomb         
                  explode("Это был правильный выбор, но вы не успели!")      
          else:
              #explode the bomb
              explode("Этот %s провод был проводом детонатора ;(" % wirecolor[hminfo['wire']])
    


def explode(m):
    """
    blow the bomb
    """
    message(m)
    hminfo['exploding'] = 1
    #### TODO ###### es_xsetinfo CheapBombTimer_TotalBeeps -1
    es.setindexprop(hminfo['bombentity'],"CPlantedC4.m_flC4Blow",'1.0')


def killpopup():
    popuplib.unsendname('ct_menu',es.getUseridList())
    popuplib.unsendname('ct_menu2',es.getUseridList())
    popuplib.unsendname('t_menu',es.getUseridList())
 
