import es
import playerlib
import popuplib
import gamethread
from xa import xa

#plugin information
info = es.AddonInfo()
info.name           = "Player Management"
info.version        = "0.2"
info.author         = "Hunter"
info.basename       = "xaplayers"

manage_choice = {}
manage_method = {}
manage_display = {}
manage_target = {}
manage_targetlist = {}
manage_pmenus = {}
manage_argc = {}
manage_cross_ref = {}

xaplayers                   = xa.register(info.basename)
xalanguage                  = xaplayers.language.getLanguage()
xa_adminkick_anonymous      = xaplayers.setting.createVariable('adminkick_anonymous', 0, "When an admin kicks a player, will no text be sent?")
xa_adminban_anonymous       = xaplayers.setting.createVariable('adminban_anonymous', 0, "When an admin bans a player, will no text be sent?")
xa_ban_time                 = xaplayers.setting.createVariable('ban_time', 0, "The amount of time (in minutes) to ban a player for (0 = forever)")
xa_adminswap_anonymous      = xaplayers.setting.createVariable('adminswap_anonymous', 0, "When an admin swaps a player, will no text be sent?")

def load():
    #Load Function for Player Settings for XA.
    xaplayermenu = popuplib.easymenu("xaplayermenu", "_tempcore", _select_option)
    xaplayermenu.settitle(xalanguage["choose option"])
    xaplayers.addMenu("xaplayermenu", xalanguage["manage players"], "xaplayermenu", "manage_player", "ADMIN")
    
    xaplayertargetmenu = popuplib.easymenu("xaplayertargetmenu", "_tempcore", _select_target)
    xaplayertargetmenu.settitle(xalanguage["choose target"])
    xaplayertargetmenu.addoption("player", xalanguage["select a player"])
    xaplayertargetmenu.addoption("team3", xalanguage["counter terrorists"])
    xaplayertargetmenu.addoption("team2", xalanguage["terrorists"])
    xaplayertargetmenu.addoption("all", xalanguage["all players"])
    xaplayertargetmenu.submenu(10, xaplayermenu)
    
    xaplayersuremenu = popuplib.easymenu("xaplayersuremenu", "_tempcore", _select_sure)
    xaplayersuremenu.settitle(xalanguage["are you sure"])
    xaplayersuremenu.addoption(True, xalanguage["yes"])
    xaplayersuremenu.addoption(False, xalanguage["no"])
    xaplayersuremenu.submenu(10, xaplayertargetmenu)

    xaplayers.registerOption("kick", xalanguage["kick"], _manage_kick, 1)
    xaplayers.registerOption("ban",   xalanguage["ban"], _manage_ban, 1)
    xaplayers.registerOption("swap", xalanguage["swap"], _manage_swap, 1)
    xaplayers.registerOption("spec", xalanguage["spec"], _manage_spec, 1)

def unload():
    for manage in manage_method:
        xaplayers.unregisterOption(manage)
    popuplib.delete("xaplayermenu")
    popuplib.delete("xaplayertargetmenu")
    popuplib.delete("xaplayersuremenu")
    for page in manage_pmenus:
        page.delete()
    xaplayers.unregister()
    
def _select_option(userid, choice, name):
    manage_choice[userid] = choice
    if not userid in manage_target:
        popuplib.send("xaplayertargetmenu", userid)
    else:
        _manage_player(manage_target[userid], manage_choice[userid], userid)
        del manage_target[userid]
    
def _select_target(userid, choice, name):
    if choice == "player":
        if userid in manage_pmenus:
            manage_pmenus[userid].delete()
        manage_pmenus[userid] = popuplib.construct("xamanageplayermenu"+str(userid), "players", "#all")
        manage_pmenus[userid].settitle(xalanguage["choose player"])
        manage_pmenus[userid].menuselectfb = _select_player
        manage_pmenus[userid].submenu(10, "xaplayertargetmenu")
        manage_pmenus[userid].send(userid)
    else:
        if choice == "team3":
            playerlist = playerlib.getUseridList("#ct")
        elif choice == "team2":
            playerlist = playerlib.getUseridList("#t")
        elif choice == "all":
            playerlist = es.getUseridList()
        if playerlist:
            manage_targetlist[userid] = playerlist
            popuplib.send("xaplayersuremenu", userid)
        else:
            popuplib.send("xaplayertargetmenu", userid)

def _select_sure(userid, choice, name):
    if choice and manage_targetlist[userid] and manage_choice[userid]:
        for player in manage_targetlist[userid]:
            _manage_player(player, manage_choice[userid], userid)
    else:
        popuplib.send("xaplayertargetmenu", userid)

def _select_player(userid, choice, name):
    _manage_player(choice, manage_choice[userid], userid)
    
def _command_player():
    adminid = es.getcmduserid()
    if adminid > 0:
        admin = playerlib.getPlayer(adminid)
    cmd = es.getargv(0).replace(str(es.ServerVar('xa_sayprefix')), 'xa_', 1).replace('ma_', 'xa_', 1)
    if cmd in manage_cross_ref:
        option = manage_cross_ref[cmd]
        if option in manage_argc:
            argc = es.getargc()
            if argc > manage_argc[option]:
                args = []
                for i in range(1, argc):
                    args.append(es.getargv(i))
                user = es.getargv(1)
                for userid in playerlib.getUseridList(user):
                    _manage_player(userid, option, adminid, args)
            elif adminid > 0:
                es.tell(adminid, xalanguage("not enough args", (), admin.get("lang")))
            else:
                es.dbgmsg(0, xalanguage("not enough args"))

def _manage_player(userid, option, adminid, args = [], force = False):
    if adminid == 0 or xaplayers.isUseridAuthorized(adminid, option+"_player") or force:
        if (not xaplayers.isUseridAuthorized(userid, "immune_"+option)) or (userid == adminid) or force:
            if callable(manage_method[option]):
                xaplayers.logging.log("Player "+es.getplayername(adminid)+ " used option "+str(option)+" on player "+es.getplayername(userid))
                try:
                    manage_method[option](userid, adminid, args, force)
                except TypeError:
                    try:
                        manage_method[option](userid, adminid, args)
                    except TypeError:
                        manage_method[option](userid, adminid)
                return True
            else:
                es.dbgmsg(0, "xaplayers.py: Cannot find method '"+str(manage_method[option])+"'!")
                return False
        else:
            es.tell(adminid, xalanguage("immune", {'username':es.getplayername(userid)}, playerlib.getPlayer(adminid).get("lang")))
            return False
    else:
        es.tell(adminid, xalanguage("not allowed", (), playerlib.getPlayer(adminid).get("lang")))
        return False

def registerOption(module, option, name, method, argc = 0):
    if not option in manage_method:
        manage_method[option] = method
        manage_display[option] = name
        manage_argc[option] = argc
        manage_cross_ref['xa_'+option] = option
        xaplayermenu = popuplib.find("xaplayermenu")
        xaplayermenu.addoption(option, name, 1)
        xaplayers.registerCapability("immune_"+option, "ADMIN", "IMMUNITY")
        if manage_argc[option] > 0:
            xaplayers.addCommand('xa_'+option, _command_player, option+"_player", "ADMIN", name["en"]+" option", True).register(('say', 'console','server'))
        return True
    else:
        return False
    
def unregisterOption(module, option):
    if option in manage_method:
        xaplayermenu = popuplib.find("xaplayermenu")
        xaplayermenu.addoption(option, 'Unloaded', 0)
        if manage_argc[option] > 0:
            xaplayers.delCommand('xa_'+option)
        manage_method[option] = None
        try:
            del manage_display[option]
            del manage_argc[option]
            del manage_cross_ref['xa_'+option]
        except:
            pass
        return True
    else:
        return False
        
def managePlayer(option, userid, adminid, args = [], force = False):
    if option in manage_method:
        return _manage_player(userid, option, adminid, args, force)
    else:
        return False

def sendPlayersMenu(userid, victimid):
    for user in list(userid):
        manage_target[user] = victimid
        xaplayermenu.send(user)

# The default options that ship with the module
def _manage_kick(userid, adminid, args):
    if str(xa_adminkick_anonymous) == '0':
        tokens = {}
        tokens['admin']   = es.getplayername(adminid)
        tokens['user']    = es.getplayername(userid)
        for user in playerlib.getPlayerList():
            es.tell(user, xalanguage("admin kick", tokens, user.get("lang")))
    es.server.cmd("kickid "+str(userid)+" Kicked by Admin")

def _manage_ban(userid, adminid, args):
    if len(args) > 1:
        bantime = args[1]
    else:
        bantime = xa_ban_time
    if str(xa_adminban_anonymous) == '0':
        tokens = {}
        tokens['admin']   = es.getplayername(adminid)
        tokens['user']    = es.getplayername(userid)
        for user in playerlib.getPlayerList():
            if int(bantime) > 0:
                tokens['time']    = xalanguage("bantime", {'min': str(bantime)}, user.get("lang"))
            else:
                tokens['time']    = xalanguage("banperm", {}, user.get("lang"))
            es.tell(user, xalanguage("admin ban", tokens, user.get("lang")))
    es.server.cmd("banid "+str(bantime)+" "+str(userid)+" kick")

def _manage_swap(userid, adminid, args):
    if str(xa_adminswap_anonymous) == '0':
        tokens = {}
        tokens['admin']   = es.getplayername(adminid)
        tokens['user']    = es.getplayername(userid)
        for user in playerlib.getPlayerList():
            es.tell(user, xalanguage("admin swap", tokens, user.get("lang")))
    if int(es.getplayerteam(userid)) == 2:
        gamethread.queue(es.changeteam, (int(userid), "3"))
    elif int(es.getplayerteam(userid)) == 3:
        gamethread.queue(es.changeteam, (int(userid), "2"))

def _manage_spec(userid, adminid, args):
    if str(xa_adminswap_anonymous) == '0':
        tokens = {}
        tokens['admin']   = es.getplayername(adminid)
        tokens['user']    = es.getplayername(userid)
        for user in playerlib.getPlayerList():
            es.tell(user, xalanguage("admin spec", tokens, user.get("lang")))
    if int(es.getplayerteam(userid)) != 1:
        gamethread.queue(es.changeteam, (int(userid), "1"))
