# Zope extension for cooledit
#

from cooledit import *
import sys, Xmlrpclib

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

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

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

def insert_resource():
    r = prompt_open_resource(gettext ("Open Resource"))
    if not r:
	return
    url, user, passw = r
    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 save_resource():
    r = prompt_open_resource(gettext ("Save Into Resource"))
    if not r:
	return
    url, user, passw = r
    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 new_resource():
    r = prompt_new_resource()
    if not r:
	return
    info, ismethod = r
    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

