import sys
sys.add_package("javax.swing")
sys.add_package("java.awt")
sys.add_package("java.io")
sys.add_package("java.awt.event")
sys.add_package("com.objexcel.irc")
sys.add_package("com.objexcel.objirc")
sys.add_package("com.objexcel.chataddin")
sys.add_package("com.objexcel.util")
sys.add_package("com.objexcel.gui")
sys.add_package("org.python.core")
sys.path.append('d:\java\jpython\lib')
import java
import javax
from javax import swing
from java import awt
from java.awt.event.KeyEvent import VK_UP, VK_DOWN
from java.awt.event import ActionEvent
from java.lang import Thread, System
from javax.swing import JFrame
from strop import *
from com.objexcel import chataddin
from com.objexcel import objirc
from com.objexcel import util
from com.objexcel import irc
from com.objexcel import gui
from java import io
from com.objexcel.irc import IRCMessageAdapter
from com.objexcel.irc.InfoListener import SERVERINFO
#from com.objexcel.irc import *
#from com.objexcel.chataddin import *

class Demo(IRCMessageAdapter, chataddin.IAddInInputListener):
    """
    Adds an irc message listener
    creates a addin window
    does an echo on whatever the user types into the script panel
    remove the irc listener when its window closes
    """
    def __init__(self, context):
        self.context = context
        
        #register us as an iRCMessage listener
        self.context.addIRCMessageListener(self)
        
        #get us our own window
        self.ourAddInWin = context.createAddInWindow("win name", "win tip")
        
        #hook into it so we can hear what is typed into it (onUserInput, onWindowClosed)
        self.ourAddInWin.addAddInInputListener(self)
        
        self.ourAddInWin.addMsg("Test.py has created an add in win", 0)
        
        #IAddInApp: Sender getSender() ;
        #lets join the objirc chat room on dalnet (I sometimes go there to test features)
        self.context.getSender().sendJoin("#objircchat")

        #IAddInApp: IAddInWin getStatusWindow()
        #demonstrate putting output in status window, getting the users current nick
        self.context.getStatusWindow().addNotice(self.context.getNick(), "Your nickname is %s" % (self.context.getNick()))
    
        #IAddInApp: Enumeration getRoomWindows()
        #demonstrate getting the names of each room
        enum = self.context.getRoomWindows()
        self.context.statusWindow.addMsg("Test.py is enumerating the current rooms:",0)
        while enum.hasMoreElements():
            self.context.statusWindow.addMsg("    room = %s" % (enum.nextElement()).target, 1)
        
        #IAddInApp: IAddInWin getRoomWindow(String lowerRoomName) ;
        # demonstrate getting a particular room window
        roomwin = self.context.getRoomWindow("#newbies")
        if(None == roomwin):
            self.context.statusWindow.addMsg("Test.py says there is no #newbies window",0)
        else:
            roomwin.addMsg("Test.py says hi in the #newbies window!",0)

        #IAddInApp: com.objexcel.objirc.RoomOccupants getRoomOccupants(String lowerRoomName) ;
        #demonstrate how to see who is in a room 
        occupants = self.context.getRoomOccupants("#newbies")
        if(occupants!=None):
            #she's always in here!
            info = occupants.getInfoForNick("skyh")
            if(info!=None):
                roomwin.addMsg("Test.py says skyh has spoken %d times" % (info[objirc.RoomOccupants.IMSG]),0)
            else:
                roomwin.addMsg("Test.py says skyh not in the room",0)
        else:
            self.context.statusWindow.addMsg("Test.py says there are no occupants listed for #newbies",0)
            
        #IAddInApp: Enumeration getChatWindows() ;
        #demonstrate access to the private chat windows
        enum = self.context.getChatWindows()
        self.context.statusWindow.addMsg("Test.py is enumerating the current chat windows:",0)
        target = None
        while enum.hasMoreElements():
            target = (enum.nextElement()).target
            self.context.statusWindow.addMsg("    chatting with %s" % target, 1)

        #IAddInApp: IAddInWin getChatWindow(String lowerFriendName) ;
        #lower is from strop
        if(target!=None):
            target = lower(target)
            chatwin = self.context.getChatWindow(target)
            chatwin.addMsg("Test.py is now writing to a private chat window", irc.InfoListener.SERVERINFO)
        else:
            self.context.statusWindow.addMsg("Test.py says there are no private chat windows open", irc.InfoListener.SERVERINFO)
        
        #IAddInApp: String getCommandLine();
        context.statusWindow.addMsg("Test.py says the command line was %s" % self.context.commandLine, irc.InfoListener.OBJIRCINFO)
        
        #IAddInApp: IChatAddIn getChatAddIn();
        context.statusWindow.addMsg("Test.py describes its purpose: %s" % self.context.chatAddIn.purpose, irc.InfoListener.OBJIRCINFO)
        
        #IAddInApp: ZipClassLoader getClassLoader();
        #IAddInApp: File getRootDir();
        #demonstrate using the class loader
        try:
            context.classLoader.load(io.File(context.rootDir, "somefile.jar"))
        except:
            context.statusWindow.addMsg("Test.py says it could not load somefile.jar", irc.InfoListener.OBJIRCINFO)            
            
    def onUserInput(self, appwinSource, input):
        """
         * This method is called with user input from a Addin
         * Window.  A tokenized copy of command is in tokens.
         * 
         * This method does nothing, override it to make
         * it more useful.
         * 
         * @see Alias for some useful parsing methods (e.g. to tokenise the input)
        public void onUserInput(String input) 
        """
        if(input == "hello"):
            components = [
                [swing.JLabel("hello there"), None]
                , [swing.JLabel("What's your name?"), swing.JTextField(20)]
                ]
            panel = gui.ArrayLayout.createLayout(components, None, None, "Hello!")
            dialog = swing.JDialog()
            dialog.contentPane.add(panel, awt.BorderLayout.CENTER)
            dialog.pack()
            dialog.show()
        else:
            self.ourAddInWin.addMsg("Test.py reapeats what you said: %s" % (input), 0)

    def onWindowClosed(self, appwinSource):
        """
         * sent when the window using this input object is closed.
         * Override it to do something if you wish.
         * 
         * BTW: listeners should remove themselves at this point
         */
        public void onWindowClosed(IAppWin source) ;
        """
        self.ourAddInWin = None
        self.context.removeIRCMessageListener(self)

        self.context.getStatusWindow().addMsg("Test.py says is has its add in window", 0)
        
        #suicide when our window closes
        self.context.unload()
        

    def vectorToString(self, vector):
        string = ""
        for i in xrange(0, vector.size()-1, 1):
            string = string + ' ' + vector.elementAt(i).toString()
        return string

    def arrayToString(self, array):
        string = ""
        for i in array:
            string = string + ' ' + i
        return string

    def hashtableToString(self, hashtable):
        string = ""
        enum = hashtable.elements()
        while enum.hasMoreElements():
            string = string + ' ' + enum.nextElement() 
        return string

	#public void onNames(IRCMessage m, String channel, String nicks[]) throws Exception;
    def onNames(self, ircMessage, sChannel, aNicks):
        self.ourAddInWin.addMsg("Test.py can report there are %d occupants in %s: %s" % (aNicks.__len__(), sChannel, self.arrayToString(aNicks)), SERVERINFO)

"""
An instance of this class will run when the script is run (/run py test).  The
user must have loaded this file first with /load py test.py
"""
class test(chataddin.IChatAddIn):
    def init(self, addInAppCotext):
        """
         * called after the addin is created, allows the addin to grab hold of 
         * the app context.
        public void init(IAddInApp context);
        """
        self.addInApp = addInAppCotext
        self.addInApp.getStatusWindow().addMsg(gui.IRCColorText.BOLD 
            + "Test.py"
            + gui.IRCColorText.PLAIN
            #+ gui.IRCColorText.COLOR + gui.IRCColorText.COL_LIGHTRED
            + gui.IRCColorText.COLOR + "4"
            + " says it is starting up", SERVERINFO)
        Demo(addInAppCotext)

    def unload(self):
        """
         * unload is called just prior to the addin being dumped.  Lets your addin perform
         * cleanup before it is shutdown.
          public void unload();
        """
        self.addInApp.getStatusWindow().addMsg("Test.py is unloading %s" % self.name, SERVERINFO)

    def getName(self):
        """
         * Returns the addin name.
        public String getName();
        """
        return "Test"
        
    def getAuthorInfo(self):
        """
         * Returns info on the add-ins author.  May include name, email address and/or download URL.
        public String getAuthorInfo();
        """
        return "Peter Bryant, support@objexcel.com, http://objexcel.com"

    def getPurpose(self) :
        """
         * Return what the addin does.
        public String getPurpose();
        """
        return "Test demonstates how to write scripts for Objirc Chat"
        
    def getHelp(self):
        """
         * Return any information needed to use or set up the addin.
        public String getHelp();
        """
        return "Type /hello in the add in window we create and see what happens"

"""
This command will run when the script is loaded (/load py test.py).  The file will also be
parsed for correctness and classes compiled and cached.
"""
if __name__ == '__main__':
    System.out.println("Test.py was loaded.  To run me, type /run py test")
