import string
import socket
import os
import time
import sys
import getpass
import operator
import signal
import traceback
import codecs
import locale
import SocketWrapper
import pprint
from IMCom import IMCom, errorCodes
from Colors import *

# do idle time in a better spot than at the end of every command.
terminalWidth = 80

def mySort(x, y):
    a,b = x
    c,d = y
    return cmp(b,d)


def setCIColors(prefs, profile):
    global usercolor, statuscolor, errorcolor, messagebodycolor,\
           timecolor, desccolor, sepcolor, defaultcolor, keycolor
    g = prefs.defaultcolors.colorsdict
    usercolor = g["user"]
    statuscolor = g["status"]
    errorcolor = g["error"]
    messagebodycolor = g["messagebody"]
    timecolor = g["time"]
    desccolor = g["desc"]
    sepcolor = g["sep"]
    defaultcolor = g["default"]
    keycolor = g["key"]

    t = profile.colors.colorsdict
    if t.has_key("user"):
        usercolor = t["user"]
    if t.has_key("status"):
        statuscolor = t["status"]
    if t.has_key("error"):
        errorcolor = t["error"]
    if t.has_key("messagebody"):
        messagebodycolor = t["messagebody"]
    if t.has_key("time"):
        timecolor = t["time"]
    if t.has_key("desc"):
        desccolor = t["desc"]
    if t.has_key("sep"):
        sepcolor = t["sep"]
    if t.has_key("default"):
        defaultcolor = t["default"]
    if t.has_key("key"):
        keycolor = t["key"]


def getTerminalWidth():
    terminalWidth = 80 #linelength

def yesnostr( val ):
    if( val ):
        return "yes"
    else:
        return "no"

def truefalsestr( val ):
    if( val ):
        return "true"
    else:
        return "false"

#def logDebug(s):
#    print s #unicode(s.encode('ascii','replace'))


def bangCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. Usage: " + cli.prefs.getCommand(cli.profile,"bang") +
              " ls ~")
        return
    os.system(line)
    return

def quitCommand(cli, line):
    for key in cli.socketlisteners:
        key.sendData("Server shutting down.\n")
        key.disconnect()
    cli.imcom.disconnect()
    cli.autostatus.kill()
    cli.running = 0
    return


def submitvcardCommand(cli, line):
    params = string.split(line, None, 4)
    if(len(params) != 5):
        cli.output("Too few arguments. Usage: /submitinfo " +
              " Casey Crabb Casey Airog crabbkw@nafai.dyndns.org \n" +
              cli.prefs.getCommand(cli.profile, "submitvcard") + " DisplayName FamilyName GivenName NickName Email")
        return
    fn = params[0]
    f  = params[1]
    g  = params[2]
    n  = params[3]
    e  = params[4]
    cli.output("Submitting your vCard to the server.")
    cli.imcom.sendSetInfo(fn,f,g,n,e)
    return



def adminCommand(cli, line):
    params = string.split(line, None, 1)
    body = None
    to = None
    if(len(params) != 2):
        cli.output("Too few arguments. Usage:  " + cli.prefs.getCommand(cli.profile,"admin") +
              "floobin.cx announce/online")
        cli.output(" or floobin.cx annouce/motd")
        return
    to = params[0]
    res = params[1]
    cli.output("Composing a message to users of " + to + " for res: " + res)
    body = cli.getAllText("msg")
    if(body == None or len(body)==0):
        cli.output("Message " + errorcolor + "cancelled" + defaultcolor)
        return
    thread = None
    cli.imcom.sendMessage(to, body, thread, res)
    cli.output("Sent a message to " + usercolor + to + defaultcolor)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return


def adminwhoCommand(cli, line):
    cli.output("Retrieving the list of all users online.. hold on a sec..")
    body = "<iq type='get' to='"
    body = body + cli.profile.server
    body = body + "'><query xmlns='jabber:iq:admin'><who/></query></iq>"
    cli.imcom.sendPacket(body)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return


def logsCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params) > 1):
        cli.output("Too many arguments.\nI can take at most one" +
              " argument - the nick or JID to view logs for" )
        return
    if( len(params) == 1 ):
        messages = cli.loghandler.readLogs( params[0], None,\
                                            None, None, None, 1 )
    else:
        messages = cli.loghandler.readLogs( None, None, None,\
                                            None, None, 1 )
    for x in messages:
        cli.loghandler.displayMessage( x )
    return



def msgrCommand(cli, line):
    params = string.split(line, None, 1)
    body = None
    to = None
    if(len(params) != 2):
        cli.output("Too few arguments. Usage: " + cli.prefs.getCommand(cli.profile,"msgr") +
              " airog@jabber.org the resource I'm at")
        return
    if( cli.profile.switches["statusnag"][0] == "true" ):
        cli.statusNag()
    to = params[0]
    jid,resource = cli.getJID(to)
    res = params[1]
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              "no such user: " + usercolor + to + defaultcolor)
        return
    cli.output("Composing a message to " + usercolor + to + defaultcolor +
          " on resource: " + keycolor + params[1] + defaultcolor)
    if(cli.useNickAsPrompt):
        body = cli.getAllText(to)
    else:
        body = cli.getAllText( "msg" )
    if(body == None or len(body)==0):
        cli.output("Message " + errorcolor + "cancelled" + defaultcolor)
        return
    thread = None
    if(cli.threadHash.has_key(jid)):
        thread = cli.threadHash[jid]
    else:
        thread = None

    cli.imcom.sendMessage(jid, body, thread, res)
    cli.lastMessaged = jid
    cli.output("Sent a message to " + usercolor + to + defaultcolor)
    cli.logMessage(jid,cli.profile.user+"@"+cli.profile.server,
                    cli.getDate(),cli.getTime(),body)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return


def msgCommand(cli, line):
    params = string.split(line,None,1)
    body = None
    to = None
    # begin add by ted
    multi_to = None
    multi_message_p = None
    multi_jids = None
    # end add by ted

    if(len(params) == 1):
        if( cli.profile.switches["statusnag"][0] == "true" ):
            cli.statusNag()
        to = params[0]
        # begin add by ted
        multi_to = string.split(to, ',')
        if len(multi_to) <= 1:
            # end add by ted
            jid,resource = cli.getJID(to)
            if(not cli.checkto(jid)):
                cli.output(errorcolor + "Error: " + defaultcolor +
                      "no such user: " + usercolor + to + defaultcolor)
                return
        cli.output("Composing a message to " + usercolor + to +
              defaultcolor)
        if(cli.useNickAsPrompt):
            body = cli.getAllText(to)
        else:
            body = cli.getAllText( "msg" )
        if(body == None or len(body)==0):
            cli.output("Message " + errorcolor + "cancelled" + defaultcolor)
            return
    elif(len(params)<2):
        cli.output("Too few arguments. Usage: " + cli.prefs.getCommand(cli.profile,"msg") +
              " airog@jabber.org hi there!")
        return

    if( cli.profile.switches["statusnag"][0] == "true" ):
        cli.statusNag()
    if(body == None):
        body = params[1]
    to = params[0]

    # begin add by ted
    if (len(params) != 1):
        multi_to = string.split(to, ',')
    multi_message_p =  (len(multi_to) > 1)
    multi_jids = []

    if multi_message_p:
        for to in multi_to:
            if len(to) == 0:
                continue
            jid,resource = cli.getJID(to)
            if (resource != None and resource != ""):
                multi_jids.append(jid + "/" + resource)
            else:
                multi_jids.append(jid)
            to = cli.getNick(jid)

            if (not cli.checkto(jid)):
                cli.output(errorcolor + "Error: " + defaultcolor +
                           "No such user: " + usercolor + to + defaultcolor)
                return

        # I'm passing the buck on your scary threading.
        thread = None
    else:
        # end add by ted. note: following lines have been indented.
        jid,resource = cli.getJID(to)
        to = cli.getNick(jid)
        if(not cli.checkto(jid)):
            cli.output(errorcolor + "Error: " + defaultcolor +
                  "No such user: " + usercolor + to + defaultcolor)
            return
        thread = None
        if(cli.threadHash.has_key(jid)):
            thread = cli.threadHash[jid]
        else:
            thread = None
        if(resource != None and resource != ""):
            jid = jid + "/" + resource

    if multi_message_p:
        cli.imcom.sendMultiMessage(multi_jids, body, thread)
        for to in multi_to:
            if(len(to) == 0):
                continue
            cli.output("Sent a message to "+ usercolor + to + defaultcolor)

        cli.logMultiMessage(multi_jids, cli.profile.user +
                            "@" + cli.profile.server,
                            cli.getDate(), cli.getTime(), body)
        cli.autostatus.setIdleTime( 0 )
        cli.autostatus.doAutoStatus()
        return
    else:
        cli.imcom.sendMessage(jid, body, thread)
        cli.lastMessaged = jid
        if(not cli.imcom.conferences.has_key(jid)):
            cli.output("Sent a message to " + usercolor + to + defaultcolor)
        cli.logMessage(jid,cli.profile.user+"@"+cli.profile.server,
                       cli.getDate(),cli.getTime(),body)
        cli.autostatus.setIdleTime( 0 )
        cli.autostatus.doAutoStatus()
        return

def idleCommand(cli, line):
    params = string.split(line, None, 1)
    cli.autostatus.setIdleTime( int( params[0] ) )
    cli.autostatus.doAutoStatus()
    return

def lastCommand(cli, line):
    params = string.split(line, None, 1)
    if len(params) == 0:
        cli.output( sepcolor + \
                    "You have messaged the following people:" + \
                    defaultcolor )
        for x in cli.lastToDict.keys():
            cli.output( usercolor + cli.getNick( x ) + defaultcolor )
        cli.output( sepcolor + \
                    "The following people have messaged you:" + \
                    defaultcolor )
        for x in cli.lastFromDict.keys():
            cli.output( usercolor + cli.getNick( x ) + defaultcolor )
        return

    if len(params) == 2:
        messages = cli.loghandler.readLogs( params[0], -1, -1,\
                                                None, params[1], 0 )
        for x in messages:
            cli.loghandler.displayMessage( x )
        return

    jidL = cli.getJID( params[0] )
    jid = jidL[0]
    target = params[0]
    if( jid == target ):
        cli.output( desccolor + "Note: " + usercolor + target +\
                    defaultcolor + " is not in your roster" )

    if( not cli.lastToDict.has_key( jid ) ):
        cli.output( "You haven't said anything to " + \
                    usercolor + target + defaultcolor )
    else:
        cli.output( usercolor + cli.profile.user + "@" +\
                    cli.profile.server + defaultcolor + " -> " + \
                    usercolor + target + "\n" + messagebodycolor +\
                    cli.lastToDict[jid] + defaultcolor )

    if( not cli.lastFromDict.has_key( jid ) ):
        cli.output( usercolor + target + defaultcolor + \
                    " hasn't said anything to you" )
    else:
        cli.output( usercolor + target + defaultcolor + " -> " + \
                    usercolor + cli.profile.user + "@" + \
                    cli.profile.server + "\n" + messagebodycolor +\
                    cli.lastFromDict[jid] + defaultcolor )
    return


def eCommand(cli, line):
    cli.printOnlineRoster()
    return

def wCommand(cli, line):
    cli.printRoster()
    return

def addCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage: " + cli.prefs.getCommand(cli.profile,"add") +
              " airog@jabber.org airog")
        return
    to = params[0]
    if(to[0] == "$" and len(to) == 2):
        n = int(to[1])
        if(len(cli.userQueue)>n):
            to = cli.userQueue[n]
    if(-1 == string.find(to,"@")):
        cli.output(errorcolor + "ERROR: " + defaultcolor + to +
                   " isn't a fully qualified jabber ID. \nUsage: " +
                   cli.prefs.getCommand(cli.profile,"add") + " airog@jabber.org airog")
        return
    nick = params[1]
    cli.imcom.sendSubscribe(to)
    cli.imcom.setNick(to, nick)
    cli.output("Sending subscribe request to " + usercolor + to +
          defaultcolor + " and renaming to " + usercolor + nick +
          defaultcolor)
    return



def authCommand(cli, line):
    if(len(line)==0):
        cli.output("Too few arguments. usage: " + cli.prefs.getCommand(cli.profile,"auth") +
              " airog@jabber.org")
        return
    to = line
    jid,resource = cli.getJID(to)
    to = cli.getNick(jid)
    #if(not cli.checkto(jid)):
    #     print(errorcolor + "Error: " + defaultcolor +
    #           jid + " is not a proper Jabber ID or not on userlist")
    #     return
    cli.imcom.sendSubscribed(jid)
    cli.output("Authorizing " + usercolor + to + defaultcolor +
          " to add you to their roster")
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return


def removeCommand(cli, line):
    if(len(line)==0):
        cli.output("Too few arguments. usage: " +
              cli.prefs.getCommand(cli.profile,"remove") +
              " airog@jabber.org")
        return
    to = line
    jid,resource = cli.getJID(to)
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    cli.imcom.sendUnsubscribe(jid)
    cli.output("Attempting to unsubscribe from " + usercolor + to +
          defaultcolor + "'s presence")
    return


def replyCommand(cli, line):
    if(cli.lastMessaged == None):
        cli.output("You have to message somebody first.")
        return
    body = line
    to = cli.lastMessaged
    nick = cli.getNick(to)
    if(len(line) == 0):
        cli.output("Composing a message to " + usercolor + nick +
              defaultcolor)
        if(cli.useNickAsPrompt):
            body = cli.getAllText(nick)
        else:
            body = cli.getAllText("msg")
        if(body == None or len(body)==0):
            cli.output("Message " + errorcolor + " cancelled" + defaultcolor)
            return

    cli.lastMessaged = to

    thread = None
    if(cli.threadHash.has_key(to)):
        thread = cli.threadHash[to]
    else:
        thread = None

    cli.imcom.sendMessage(to, body, thread)
    if(not cli.imcom.conferences.has_key(to)):
        cli.output("Sent a message to " + usercolor + nick + defaultcolor)
    cli.logMessage(to,cli.profile.user+"@"+cli.profile.server,
                   cli.getDate(),cli.getTime(),body)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return


def respondCommand(cli, line):
    if(cli.lastReceived == None):
        cli.output("Someone has to message you first.")
        return

    to = cli.lastReceived
    nick = cli.getNick(to)
    body = line
    if(len(line) == 0):
        cli.output("Composing a message to " + usercolor + nick +
              defaultcolor)
        if(cli.useNickAsPrompt):
            body = cli.getAllText(nick)
        else:
            body = cli.getAllText("msg")
        if(body == None or len(body)==0):
            cli.output("Message " + errorcolor + " cancelled" + defaultcolor)
            return
    thread = None
    if(cli.threadHash.has_key(to)):
        thread = cli.threadHash[to]
    else:
        thread = None
    cli.imcom.sendMessage(to, body, thread)
    cli.lastMessaged = to
    cli.output("Sent a message to " + usercolor + nick + defaultcolor)
    cli.logMessage(to,cli.profile.user+"@"+cli.profile.server,
                   cli.getDate(),cli.getTime(),body)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return



def setpriorityCommand(cli, line):
    if(len(line) == 0):
        priority = 0
    else:
        try:
            priority = int(line)
        except:
            cli.output("Priority must be a number. (-1, 0, 1, 49574, etc)")
            return
    cli.profile.priority = priority
    cli.output("Setting base priority to " + statuscolor + str(priority) + defaultcolor)
    if(cli.currentStatus == "online" or cli.currentStatus == "chat"):
        cli.imcom.sendPriority(priority)
    elif(cli.currentStatus == "away"):
        cli.imcom.sendPriority(priority-2)
    elif(cli.currentStatus == "xa"):
        cli.imcom.sendPriority(priority-4)
    elif(cli.currentStatus == "dnd"):
        cli.imcom.sendPriority(priority-6)
    cli.autostatus.doAutoStatus()
    return

def onlineCommand(cli, line):
    reason = ""
    if(len(line) != 0):
        reason = line
    cli.currentStatus = "online"
    cli.currentStatusReason = reason
    cli.autostatus.statusChange( cli.currentStatus, cli.currentStatusReason )
    cli.imcom.sendOnline(reason)
    cli.output("Setting status to " + statuscolor + "online" +
          defaultcolor)
    cli.autostatus.doAutoStatus()
    return


def awayCommand(cli, line):
    if(len(line) == 0):
        reason = "I'm too lazy to enter why I'm away"
    else:
        reason = line
    cli.currentStatus = "away"
    cli.currentStatusReason = reason
    cli.imcom.sendAway(reason)
    cli.output("Setting status to " + statuscolor + "away" + defaultcolor +
          " with reason: " + desccolor + reason + defaultcolor)
    cli.autostatus.statusChange( cli.currentStatus, cli.currentStatusReason )
    cli.autostatus.doAutoStatus()
    return


def chatCommand(cli, line):
    cli.currentStatus = "chat"
    cli.currentStatusReason = ""
    cli.imcom.sendChat()
    cli.output("Setting status to " + statuscolor + "chat" + defaultcolor)
    cli.autostatus.statusChange( cli.currentStatus, cli.currentStatusReason )
    cli.autostatus.doAutoStatus()
    return


def xaCommand(cli, line):
    if(len(line) == 0):
        reason = "I'm too lazy to enter why I'm xa"
    else:
        reason = line
    cli.currentStatus = "xa"
    cli.currentStatusReason = reason
    cli.imcom.sendXA(reason)
    cli.output("Setting status to " + statuscolor + "xa" + defaultcolor +
          " with reason: " + desccolor + reason + defaultcolor)
    cli.autostatus.statusChange( cli.currentStatus, cli.currentStatusReason )
    cli.autostatus.doAutoStatus()
    return


def dndCommand(cli, line):
    if(len(line) == 0):
        reason = "I'm too lazy to enter why I'm dnd"
    else:
        reason = line
    cli.currentStatus = "dnd"
    cli.currentStatusReason = reason
    cli.imcom.sendDND(reason)
    cli.output("Setting status to " + statuscolor + "dnd" + defaultcolor +
          " with reason: " + desccolor + reason + defaultcolor)
    cli.autostatus.statusChange( cli.currentStatus, cli.currentStatusReason )
    cli.autostatus.doAutoStatus()
    return


def infoCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. usage:" + cli.prefs.getCommand(cli.profile,"info") +
              " airog@jabber.org")
        return
    jid,resource = cli.getJID(line)
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    cli.output("Trying to retrieve information on " + usercolor +
          line + defaultcolor)
    cli.imcom.sendGetInfo(jid)
    return


def setCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage:" + cli.prefs.getCommand(cli.profile,"set") +
              " statusShow off")
        cli.output("The values are boolean and can be on, off, true, false, yes, no")

        maxwidth = 0
        for x in cli.profile.switches.keys():
            if maxwidth < len( cli.profile.switches[x][1]):
                maxwidth = len( cli.profile.switches[x][1] )
        for x in cli.profile.switches.keys():
            cli.output( keycolor +
                   string.ljust( cli.profile.switches[x][1],
                                 maxwidth + 3 ) + ": " +
                   desccolor + cli.profile.switches[x][0] +
                   defaultcolor )
        return

    variable = string.lower(params[0])
    value = string.lower(params[1])
    if(value == "on" or value == "true" or value == "yes"):
        value = 1
    else:
        value = 0

    if( cli.profile.switches.has_key( variable ) ):
        cli.profile.switches[variable] = \
                                       [ truefalsestr( value ),
                                         cli.profile.switches[variable][1],
                                         cli.profile.switches[variable][2] ]
        cli.output( desccolor +
                    cli.profile.switches[variable][2] + "   " +
                    statuscolor + yesnostr( value ) +
                    defaultcolor )
    else:
        cli.output( "Unknown variable " + statuscolor + params[0]
                    + defaultcolor )
        return

    if(variable == "statusshow"):
        cli.showPresenceUpdates = value
        return
    if(variable == "debug"):
        cli.debug=value
        cli.imcom.setDebug(value)
        return
    if(variable == "colors"):
        if(value):
            cli.setColors()
        else:
            cli.setNoColors()
        return
    if(variable == "ringbell"):
        cli.ringBell = value
        return
    if(variable == "nickprompt"):
        cli.useNickAsPrompt = value
        return
    if(variable == "allowinterruptions"):
        cli.allowInterrupt = value
        return
    return


def renameCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage:" + cli.prefs.getCommand(cli.profile,"rename") +
              " airog sairog")
        return
    jid,resource = cli.getJID(params[0])
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    name = params[1]
    cli.output("Attempting to set " + usercolor + jid + defaultcolor +
          "'s nick to " + usercolor + name + defaultcolor)
    cli.imcom.setNick(jid,name)
    return



def deleteCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. usage:" + cli.prefs.getCommand(cli.profile,"delete") +
              " airog")
        cli.output(errorcolor + "WARNING: " + defaultcolor +
              "This command " +
              "deletes all subscriptions in regards to " +
              "roster item deleted. If they are currently " +
              "subscribed to your presence they will nolonger " +
              "be after this command is successfully issued")
        return
    jid,resource = cli.getJID(line)
    #if(not cli.checkto(jid)):
    #     print(errorcolor + "Error: " + defaultcolor +
    #           jid + " is not a proper Jabber ID or not on userlist")
    #     return
    cli.output("Completely " + errorcolor + "obliterating" + defaultcolor +
          " all subscription and roster " +
          "information for " + usercolor + jid + defaultcolor)
    cli.imcom.removeUser(jid)
    return



def listprofilesCommand(cli, line):
    keys = cli.prefs.profiles.keys()
    cli.output("You have " + timecolor + "%d"%len(keys) +
          defaultcolor + " profiles")
    for item in keys:
        cli.output(cli.prefs.profiles[item].name)
    cli.output("")
    return



def switchprofileCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"switchprofile") +
              " jabber.org")
        return
    if(cli.prefs.profiles.has_key(string.strip(line))):
        cli.profile = cli.prefs.profiles[string.strip(line)]
        cli.output("Switching to " + line + ", hold on a sec...")
        cli.imcom.disconnect()
        cli.imcom = None
        cli.imcom = IMCom(cli)
        cli.lastMessaged = None
        cli.lastReceived = None
        cli.threadHash = {}
        cli.applyProfile()
        cli.applyPrefs()
        cli.loghandler.setProfile( cli.profile )
        return
    else:
        cli.output("I couldn't find a profile by the name of " + line)
        return


def showCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. usage: " +
              cli.prefs.getCommand(cli.profile,"show") +
              " lurker")
        cli.output("The following is a list of groups: ")
        keys = cli.imcom.grouphash.keys()
        for item in keys:
            if(len(cli.imcom.grouphash[item]) > 0):
                cli.output(keycolor + item + defaultcolor)
        return
    if(not cli.imcom.grouphash.has_key(line) or
       len(cli.imcom.grouphash[line]) <= 0):
        cli.output("There is no one who is a member of group: " +
              keycolor + line)
        return
    cli.showGroupMembers(line)
    return



def addgroupCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"addgroup") +
              " airog lurker")
        return
    jid,resource = cli.getJID(params[0])
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    gname = params[1]
    cli.output("Adding " + usercolor + params[0] + defaultcolor +
          " to group " + keycolor + gname + defaultcolor)
    cli.imcom.addGroup(jid,gname)
    return



def setgroupCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"setgroup") +
              " airog lurker")
        return
    jid,resource = cli.getJID(params[0])
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    gname = params[1]
    cli.output("Setting " + usercolor + params[0] + defaultcolor +
          "'s group to be " + keycolor + gname + defaultcolor)
    cli.imcom.setGroup(jid,gname)
    return



def delgroupCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params)<2):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"delgroup") +
              " airog lurker")
        return
    jid,resource = cli.getJID(params[0])
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    gname = params[1]
    cli.output("Removing " + usercolor + params[0] + defaultcolor +
          " from group " + keycolor + gname + defaultcolor)
    cli.imcom.removeGroup(jid,gname)
    return



def membershipCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"membership") +
              " airog")
        return
    jid,resource = cli.getJID(line)
    nick = cli.getNick(jid)
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    l = cli.imcom.gjidhash[jid]
    cli.output(usercolor + nick + defaultcolor +
          " belongs to the following groups:" + keycolor)
    for item in l:
        cli.output(item)
    cli.output(defaultcolor)
    return




def sendfileCommand(cli, line):
    params = string.split(line, None, 1)
    if(len(params) < 2):
        cli.output("Too few arguments. usage:" +
              cli.prefs.getCommand(cli.profile,"sendfile") +
              " airog /home/crabbkw/test.txt")
        return
    jid,resource = cli.getJID(params[0])
    res = ""
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    if(-1 == string.find(jid,'/')):
        if(not cli.imcom.reshash.has_key(jid)):
            cli.output(errorcolor + "Error: " + defaultcolor +
                  jid + " needs a resource. Fully specify the jid: " +
                  "eg: airog@floobin.cx/imcom")
            return
        res = cli.imcom.reshash[jid][0]
    else:
        res = jid[string.find(jid,"/")+1:]
    fname = params[1]
    if(not os.path.exists(fname) or not os.path.isfile(fname)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              "Path doesn't exist: " + fname)
        return
    cli.imcom.sendFile(jid+"/"+res,fname)
    return



def agentsCommand(cli, line):
    cli.output("Requesting the list of transport and agents supported")
    cli.imcom.sendAgentListRequest()
    return



def agenthelpCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"agenthelp") +
              " icq.jabber.org")
        return
    cli.output("Beginning the registration process. "\
          "Requesting required information.")
    to = line
    cli.imcom.sendAgentRegHelp(to)
    return



def agentregCommand(cli, line):
    params = string.split(line)
    if(len(params) < 2):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"agentreg") +
              " icq.jabber.org 1227626 yeah-right nobody")
        return
    to = params[0]
    fields=params[1:]
    cli.imcom.sendAgentRegistration(to,fields)
    return



def getfileCommand(cli, line):
    if(len(line)<=0):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"getfile") +
              " airog")
        return
    jid,resource = cli.getJID(line)
    if(not cli.checkto(jid)):
        cli.output(errorcolor + "Error: " + defaultcolor +
              jid + " is not a proper Jabber ID or not on userlist")
        return
    cli.imcom.getFile(jid)
    cli.autostatus.setIdleTime( 0 )
    cli.autostatus.doAutoStatus()
    return



def aliasCommand(cli, line):
    params = string.split(line,None,1)
    if(len(params) != 2):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"alias") +
              " <name> <command to issue>\n" +
              "Example " + cli.prefs.getCommand(cli.profile,'alias') +
              " today ! date\n")
        cli.output("This is the current list of aliases")
        keys = cli.profile.aliases.keys()
        for item in keys:
            cli.output(keycolor + item + defaultcolor + " : " +\
                       desccolor + cli.profile.aliases[item] + defaultcolor)
        return
    cli.output("Setting " +params[0] + " to " + params[1])
    cli.profile.aliases[params[0]]=params[1]
    return



def saveprefsCommand(cli, line):
    cli.output("Saving your preferences to ~/.imcom/imcomrc")
    cli.prefs.writePreferences()
    cli.output("Prefs saved")
    return



def unaliasCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"unalias") +
              " <aliasname>\n" +
              "Example " + cli.prefs.getCommand(cli.profile,'unalias') +
              " today\n")
        cli.output("This is the current list of aliases")
        keys = cli.profile.aliases.keys()
        for item in keys:
            cli.output(keycolor + item + defaultcolor + " : " +\
                       desccolor + cli.profile.aliases[item] + defaultcolor)
        return
    if(not cli.profile.aliases.has_key(line)):
        cli.output(errorcolor + "Error: " + keycolor + line + defaultcolor +
              " is not the name of an alias")
        return
    cli.output("Removing alias: " + keycolor + line + defaultcolor)
    del cli.profile.aliases[line]
    return

def interactiveregCommand( cli, line ):
    fields = string.split( line, "<" )
    ffrom = fields.pop(0)

    cli.output( "Now attempting to register you for the " + 
        cli.getNick( ffrom ) + " (" + ffrom + ")" )
    cli.gettingCommand = 1
    cli.mode = cli.MULTILINE

    retfields = []
    for i in fields:
        retfields.append( raw_input( i + " > " ) )

    answer = raw_input( "Send registration request (y/n)? " )

    cli.mode = 0
    cli.gettingCommand = 0

    if( ( answer[0] != "y" ) and ( answer[0] != "Y" ) ):
        cli.output( "Registration cancelled" );
        # show the messages that came in while they were busy
        cli.dumpQueue()
        return

    # show the messages that came in while they were busy
    cli.dumpQueue()
    cli.imcom.sendAgentRegistration( ffrom, retfields )

def joinconfCommand(cli, line):
    params = string.split(line,None,1)
    if(len(params) != 2):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"joinconf") +
              " <jid-of-conference> <nickname-to-assign-conference>\n" +
              "Example " + cli.prefs.getCommand(cli.profile,'joinconf') +
              " jdev@conference.jabber.org jdev\n")
        cli.output("This is the current list of conferences you are in: ")
        for key in cli.imcom.confnick:
            cli.output(keycolor + key + defaultcolor + " : " + usercolor + cli.imcom.confnick[key] + defaultcolor)
        return
    cli.output("Attemping to join conference: " + usercolor + params[0] + defaultcolor)
    cli.imcom.joinConference(params[0], params[1])
    return

def leaveconfCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"leaveconf") +
              " <conference-jid-or-conference-nick>\n" +
              "Example " + cli.prefs.getCommand(cli.profile,'leaveconf') +
              " jdev@conference.jabber.org\n")
        cli.output("This is the current list of conferences you are in: ")
        for key in cli.imcom.confnick:
            cli.output(keycolor + key + defaultcolor + " : " + usercolor + cli.imcom.confnick[key] + defaultcolor)
        return
    cli.output("attempting to leave conference: " + usercolor + line + defaultcolor)
    cli.imcom.leaveConference(line)
    return

def confusersCommand(cli, line):
    if(len(line) == 0):
        cli.output("Too few arguments. Usage: " +
              cli.prefs.getCommand(cli.profile,"confusers") +
              " <conference-jid-or-conference-nick>\n" +
              "Example " + cli.prefs.getCommand(cli.profile,'confusers') +
              " jdev@conference.jabber.org\n")
        cli.output("This is the current list of conferences you are in: ")
        for key in cli.imcom.confnick:
            cli.output(key + " : " + cli.imcom.confnick[key])
        return
    cjid = line
    if(cli.imcom.confnick.has_key(line)):
        cjid = cli.imcom.confnick[line]
    if(cli.imcom.conferences.has_key(cjid)):
        # print out the users
        for key in cli.imcom.conferences[cjid][1]:
            cli.output(usercolor + key + defaultcolor + " is " + statuscolor + cli.imcom.conferences[cjid][1][key][1] + \
                       defaultcolor + " as " + desccolor + cli.imcom.conferences[cjid][1][key][0] + defaultcolor)
    else:
        cli.output("You're not a part of conference: " + cjid)
    return


def helpCommand(cli, line):
    cli.output(sepcolor + "------------------Help-------------------" +
          defaultcolor)
    cli.output("The following commands are available: ")
    keys = cli.prefs.defaultcommands.helpcommands.keys()
    mxkeylen = 0
    hc = []
    for item in keys:
        if(len(item) > mxkeylen):
            mxkeylen = len(item)
        hc.append((item,cli.prefs.getCommand(cli.profile,item)))
    hc.sort(mySort)
    for item in hc:
        key,value = item
        cli.output(keycolor + string.ljust(value,mxkeylen+4) +
              defaultcolor + " : " + desccolor +
              cli.prefs.defaultcommands.helpcommands[key] +
              defaultcolor)
    cli.output("")
    return

