# Zope extension for cooledit
#

import sys

sys.path.insert(0, "/home/michel/dev/Zope2/lib/python")

import xmlrpclib

zope_variables = {}

zope_variables['resource_url'] = 'http://'
zope_variables['name'] = ''
zope_variables['passw'] = ''

def prompt_open_resource():
    inputs, cbs = generic_dialog('Open Resource',
	(zope_variables['resource_url'],
         zope_variables['name'],
         zope_variables['passw']),
	('Resource URL', 'Username', 'Password'),
	('xmlrpc-resource-url', 'xmlrpc-username', 'xmlrpc-password'),
	('URL to the Resource to open', 'A valid userid', 'A valid password'),
	# there are no checkboxes...
	(), (), () )
    return inputs

def prompt_new_resource():
    return generic_dialog('New Resource',
	(zope_variables['resource_url'],
         '',
         zope_variables['name'],
         zope_variables['passw']),
	('Resource Parent URL', 'Resource ID', 'Username', 'Password'),
	('xmlrpc-resource-url', 'xmlrpc-resource-id', 'xmlrpc-username',
         'xmlrpc-password'),
	('Parent URL for resource', 'Resource ID', 'A valid userid',
         'A valid password'),
	# there are no checkboxes...
	(0,), ('Create Method',), ('xmlrpc-create-method',) )

def zope_open_resource():
    # url = input_dialog('Enter URL to open', 'URL', '')
    # user = input_dialog('Enter Userid', 'userid', '')
    # passw = input_dialog('Enter Password', 'password', '')
    
    url, user, passw = prompt_open_resource()
    zope_variables['resource_url'] = url
    zope_variables['user'] = user
    zope_variables['passw'] = passw
    conn = xmlrpclib.Server(url, user, passw)
    insert(conn.document_src())
    redraw_page()
    
def zope_save_resource():
    url, user, passw = prompt_open_resource()
    zope_variables['resource_url'] = url
    zope_variables['user'] = user
    zope_variables['passw'] = passw
    conn = xmlrpclib.Server(url, user, passw)
    src = get_text(0, buffer_size())
    conn.manage_edit(src, '')
    
def zope_new_resource():
    info, ismethod = prompt_new_resource()
    url, id, user, passw = info
    zope_variables['resource_url'] = url
    zope_variables['user'] = user
    zope_variables['passw'] = passw
    conn = xmlrpclib.Server(url, user, passw)
    try:
        if ismethod[0]:
	    conn.manage_addDTMLMethod(id)
	else:
	    conn.manage_addDTMLDocument(id)
    except xmlrpclib.ProtocolError:
        # because Zope responds with a redirect which xml-rpc turns
        # into an error
	pass
    

# key bindings

key("x", ControlMask, "open_zope_resource()")

# this method is called when the file type changes

def type_change(s):
    menu("Util")
    menu("Util", "Open Resource URL...", "zope_open_resource()")
    menu("Util", "New Resource...", "zope_new_resource()")
    menu("Util", "Save Resource...", "zope_save_resource()")
