#!/usr/bin/env jpython
#
# app.py : Top-level code for running as a standalone application
#
# Distributed under the terms described in the LICENCE file.
#
# Developed by akuchlin@mems-exchange.org

__revision__ = "$Id: jmicroscope,v 1.12 2002/03/18 16:51:44 akuchlin Exp $"

import sys ; sys.path.append('/www/mxpython/mems/instrument/client/awt')

from java import awt
from java.util import Vector
from org.apache.xmlrpc import XmlRpcClient
from PyClient import PyClient

# Quoting function, copied from urllib.quote()
import string
always_safe = string.letters + string.digits + '_,.-'
def quote (s, safe = '/'):
    safe = always_safe + safe
    res = list(s)
    for i in range(len(res)):
        c = res[i]
        if c not in safe:
            res[i] = '%%%02x' % ord(c)
    return string.joinfields(res, '')

if __name__ == '__main__':
    import sys, getopt

    device = user_id = password = None
    chat = 1
    
    options, args = getopt.getopt(sys.argv[1:], 'cd:h:p:u:',
                                  ['nochat', 'help',
                                   'device=', 'user=', 'password='] )

    for (opt, param) in options:
        if opt == '-c' or opt == '--nochat': chat = 0
        elif opt == '-h' or opt == '--help':
            print """Remote Microscope client:
Usage: app.py [options]
Available options:
 -h, --help                    Display this help message
 -c, --nochat                  Disable displaying of the chat window
 -d dev, --device dev          Use device named dev (ex. 'MX')
 -u user, --user user          Set user name to 'user'
 -p pw, --password pw          Set password to 'pw'
"""
            sys.exit(0)
        elif opt == '-d' or opt == '--device':
            device = string.lower(param)
        elif opt == '-u' or opt == '--user':
            user_id = param
        elif opt == '-p' or opt == '--password':
            password = param

    if (device is None or user_id is None or password is None):
        from LoginDialog import LoginDialog
        f = awt.Frame("Microscope Login")
        d = LoginDialog( f, device, user_id, password )
        d.pack()
        d.validate()
        d.show()

        device, user_id, password = d.device, d.user_id, d.password
        
        f.hide()
        f.dispose()
        del f,d

    if user_id is None:
        # The user just closed the dialog box without filling anything in.
        import java.lang.System
        java.lang.System.exit(0)

    else:
        server = XmlRpcClient('http://www.mems-exchange.org/xml/rpc')
        v = Vector()
        v.addElement(user_id)
        v.addElement(password)
        v.addElement(device)
        result = server.execute('get_authtoken', v)
        (host, port, authtoken) = result

    c = PyClient(host, port, authtoken, user_id, None)
    c.init(chat)
    c.get_frame().pack()
    c.get_frame().validate()
    c.get_frame().show()
    c.make_connection()
        
