#!/usr/bin/env python

from string import *
from gtk import *
import _gtk
import xmlrpclib
import pysga
import sgagtk
import threading
import sys
import socket
import Numeric

try:
  import sg
except:
  sg=0

def finish_func(params):
    pass

def download_page(params,page_box,next=None,prev=None,cancel=None):
  vbox=GtkVBox()  
  page_box.pack_start(vbox)

  vbox.set_homogeneous(FALSE) 
  print "params['tags'][params['db_select']]=",params['tags'][params['db_select']]
  if not len(params['db_select']) or (not len(params['histos'][params['db_select']]) \
    and not len(params['tags'][params['db_select']])):  
    vbox.pack_start(GtkLabel("No objects selected!\n"+
     "Press 'Back' to make a selection."),expand=TRUE,fill=TRUE,padding=5)
    vbox.show_all()
    return

  label=GtkLabel("")
  vbox.pack_start(label,expand=FALSE,fill=FALSE,padding=5)
  progress=GtkProgressBar()
  progress.set_bar_style(PROGRESS_CONTINUOUS)
  progress.set_show_text(TRUE)
    
  
  hbox=GtkHBox()
  hbox.pack_start(progress,padding=5,expand=TRUE,fill=TRUE)
  vbox.pack_start(hbox,expand=FALSE,fill=FALSE,padding=5)
  histo1D=[]
  obj_dict={}
  sheet=pysga.SGworksheet(params['sheet_name'])
  vbox.show_all() 
  if params['col_choice']==0:
    cur_col=params['col_num']
  else:
    cur_col=len(sg.column_names(sheet.name))

  if not params['cont_select'] and not len(params['tags'][params['db_select']]):
    if params['obj_select'] and len(params['obj_select'])>0:
      obj_dict={params['obj_select']:params['obj_select_type']}
      progress.configure(0,0,1)
    else:
      obj_dict=params['histos'][params['db_select']]
      progress.configure(0,0,len(obj_dict.keys()))
    vbox.show_all()
    while events_pending():
      mainiteration(block=FALSE)

    keys=obj_dict.keys()
  
    
    for cnt in range(len(keys)):
      label.set_text("Downloading "+obj_dict[keys[cnt]]+" '"+keys[cnt]+"'")
      cursor = cursor_new(150 & 0xfe)
      progress.set_value(cnt)
      page_box.get_window().set_cursor(cursor)
      while events_pending():
	mainiteration(block=FALSE)
      
      print "obj_dict=",obj_dict
      
      try:
	if obj_dict[keys[cnt]]=='histogram':
	  rpc_params={"bootfile":params["fdname"],
		      "db":params['db_select'],
		      "histname":keys[cnt]}  
	  histo=params['dbsvr'].DBServer.getHisto1Dcol(rpc_params)
	  histo1D.append(histo)
	  min=histo["min"]
	  delta=(histo["max"]-histo["min"])/histo["bins"]
	  bins=Numeric.arrayrange(histo["min"]+delta/2,histo["max"],delta)
	  cols=sg.column_names(params['sheet_name'])
	  col_num=len(cols)
	  if cur_col+3>col_num:
	   sheet.add_columns(cur_col+3-col_num)
	  sheet.setcol(cur_col,bins)
	  sheet.setcol(cur_col+1,histo["values"])
	  sheet.setcol(cur_col+2,histo["errors"])
	  if params['rename_choice']:
	    sg.set_column_name(sheet.name,cur_col,keys[cnt]+"_bins")
	    sg.set_column_name(sheet.name,cur_col+1,keys[cnt]+"_values")
	    sg.set_column_name(sheet.name,cur_col+2,keys[cnt]+"_errors")
	  cur_col=cur_col+3
      except socket.error, my_except:
	try: 
	 errstring=my_except[1]
	except:
	 errstring=my_except[0]
	vbox.pack_start(GtkLabel("Unable to connect:\n"+errstring),
	expand=FALSE,fill=FALSE,padding=5)
	return
      except xmlrpclib.ProtocolError, my_except:
	vbox.pack_start(GtkLabel("XML-RPC error connecting to\n"+
	 my_except.url+":\n"+my_except.errmsg),
	expand=FALSE,fill=FALSE,padding=5)
	return
  #    except:
  #      vbox.pack_start(GtkLabel("Unknown error\n"),
  #      expand=FALSE,fill=FALSE,padding=5)
  #      return
      progress.set_value(cnt+1)
      cursor = cursor_new(68 & 0xfe)
      page_box.get_window().set_cursor(cursor)
      while events_pending():
	mainiteration(block=FALSE)
  
  else: #We're dealing with tags
    containers=params['tags'][params['db_select']].keys()
    print "containers=",containers
    for cont in containers:
      if params['tag_select']:
	tags=[params['tag_select']]
      else:
	tags=[]
	for tname in params['tags'][params['db_select']][cont].keys():
	  tags.append(tname)
      print "tags=",tags
      for tname in tags:
	if params['obj_select_type']=='Column':
	  colnames=[params['obj_select']]
	else:
	  colnames=params['tags'][params['db_select']][cont][tname]['cols']
        print "colnames=",colnames
        col_num=len(colnames)
	progress.configure(0,0,len(colnames))
	if cur_col>col_num:
	  sheet.add_columns(cur_col+1-col_num)
	
	for i in range(col_num):
	  cname=colnames[i]
	  label.set_text("Downloading "+cont+" : "+tname+" : "+cname)
	  progress.set_value(i)
          cursor = cursor_new(150 & 0xfe)
          page_box.get_window().set_cursor(cursor)
          while events_pending():
            mainiteration(block=FALSE)

          try:
	    rpc_params={"bootfile":params["fdname"],
			"db":params['db_select'],
			"contname":cont,
			"tagname":tname,  
			"colname":cname}
	    tag=params['dbsvr'].DBServer.getTagColumn(rpc_params)

            print "tag=",tag
            sheet.setcol(cur_col,tag["values"])
	    if params['rename_choice']:
	      sg.set_column_name(sheet.name,cur_col,cname)
	    cur_col=cur_col+1
	  except socket.error, my_except:
	    try: 
	      errstring=my_except[1]
	    except:
	      errstring=my_except[0]
	    vbox.pack_start(GtkLabel("Unable to connect:\n"+errstring),
	    expand=FALSE,fill=FALSE,padding=5)
	    return
	  except xmlrpclib.ProtocolError, my_except:
	    vbox.pack_start(GtkLabel("XML-RPC error connecting to\n"+
	      my_except.url+":\n"+my_except.errmsg),
	    expand=FALSE,fill=FALSE,padding=5)
	    return            
	label.set_text("Download complete")
	progress.set_value(i+1)
	cursor = cursor_new(68 & 0xfe)
	page_box.get_window().set_cursor(cursor)
	while events_pending():
	  mainiteration(block=FALSE)




def plot_col_page(params,page_box,next=None,prev=None,cancel=None):
# First create new sheet object, which may create a new physical sheet:
  mysheet=pysga.SGworksheet(params['sheet_name'])
  vbox=GtkVBox()  
  page_box.pack_start(vbox)

  vbox.set_homogeneous(FALSE)  
  if not len(params['db_select']):  
    vbox.pack_start(GtkLabel("No objects selected!\n"+
     "Press 'Back' to make a selection."),expand=TRUE,fill=TRUE,padding=5)
    vbox.show_all()
    return
  
  table = GtkTable(3, 2, FALSE)
  table.set_col_spacings(10)
  table.set_row_spacings(5) 
  vbox.pack_start(table,expand=TRUE,fill=TRUE,padding=5)
  
  dblabel=GtkLabel("Database: "+params['db_select'])
  dblabel.set_justify(JUSTIFY_LEFT)
  table.attach(dblabel, 0, 2, 0, 1,yoptions=0,xpadding=5,xoptions=0)  
  if params['obj_select'] and len(params['obj_select']):
    table.attach(GtkLabel(params['obj_select_type']+": "+params['obj_select']),0,1,
    1, 2, yoptions=0, xpadding=5, xoptions=0)
  table.attach(GtkLabel("Sheet selected: "+params['sheet_name']), 0, 2, 2, 3,yoptions=0,xpadding=5,xoptions=0)  
  table.attach(GtkHSeparator(),0,2, 3,4)    
  table.attach(GtkLabel("Start inserting in:"),0,1,
   4, 5, yoptions=0, xpadding=5, xoptions=0)      


  params['col_choice']=0
  button1 = GtkRadioButton(None, "Existing column:") 
  button1.connect("toggled",col_toggle,params,0)

  menu=GtkCombo()
  cols=sg.column_names(params['sheet_name'])
  menu.set_popdown_strings(cols)
  menu.set_value_in_list(TRUE,FALSE)
  active=mysheet.col0()
  params['col_num']=active
  menu.entry.set_text(cols[active])

  menu.entry.set_editable(FALSE)
  menu.entry.connect("changed",col_combo_changed,params)


  hbox=GtkHBox()
  hbox.pack_start(button1,expand=FALSE,fill=FALSE,padding=0)
  hbox.pack_start(menu,expand=FALSE,fill=FALSE,padding=5)
  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)

  button2 = GtkRadioButton(button1, "New column after column '"+cols[-1]+"'")
  button2.connect("toggled",col_toggle,params,1)  
  hbox=GtkHBox()  
  hbox.pack_start(button2,expand=FALSE,fill=FALSE,padding=0)
  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)
  
  vbox.pack_start(GtkHSeparator(),expand=TRUE,fill=TRUE,padding=5) 

  hbox=GtkHBox()
  button3 = GtkCheckButton(label="Rename columns using object name") 
  hbox.pack_start(button3,expand=FALSE,fill=FALSE,padding=0)
  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)
  button3.set_active(TRUE)
  params['rename_choice']=TRUE
  button3.connect("toggled",rename_toggle,params)

  vbox.show_all()

def new_sheet_name_changed(entry,params):
    params['sheet_name']=entry.get_text()    
    
def sheet_toggle(button,params,widget,value):
  params['sheet_choice']=value
  if value==0:
    params['sheet_name']=widget.entry.get_text()    
  elif value==1:
    params['sheet_name']=params['db_select']
  elif value==2:
    params['sheet_name']=widget.get_text()    

  if widget:
    if button.get_active():
      widget.set_sensitive(TRUE)
    else:
      widget.set_sensitive(FALSE)

def rename_toggle(button,params):
  params['rename_choice']=(params['rename_choice']+1)%2
  
def col_toggle(button,params,value):
  params['col_choice']=value

def sheet_combo_changed(entry,params):
  params['sheet_name']=entry.get_text()

def col_combo_changed(entry,params,cols):
  text=entry.get_text()
  cnt=0
  for col in cols:
    if col==text:
      params['col_num']=cnt
      break
    cnt=cnt+1

def create_menu(names):
  if not len(names): return None
  menu = GtkMenu()
  group = None
  for name in names:
    menuitem = GtkRadioMenuItem(group,name)
    group = menuitem
    menu.append(menuitem)
    menuitem.show()
  return menu


def plot_sheet_page(params,page_box,next=None,prev=None,cancel=None):
  vbox=GtkVBox()
  page_box.pack_start(vbox)

  vbox.set_homogeneous(FALSE)  
  if not len(params['db_select']):  
    vbox.pack_start(GtkLabel("No objects selected!\n"+
     "Press 'Back' to make a selection."),expand=TRUE,fill=TRUE,padding=5)
    vbox.show_all()
    next.set_sensitive(FALSE)
    return
  
  table = GtkTable(3, 2, FALSE)
  table.set_col_spacings(10)
  table.set_row_spacings(5) 
  vbox.pack_start(table,expand=TRUE,fill=TRUE,padding=5)
  table.attach(GtkLabel("Database: "+params['db_select']), 0, 1, 0, 1,yoptions=0,xpadding=5,xoptions=EXPAND|FILL)  


  if params['obj_select'] and len(params['obj_select'])>0:
    table.attach(GtkLabel(params['obj_select_type']+": "+params['obj_select']),0,1,
    1, 2, yoptions=0, xpadding=5, xoptions=0)    

  else:
    page_box.show_all()
    cursor = cursor_new(150 & 0xfe)
    page_box.get_window().set_cursor(cursor)
    while events_pending():
      mainiteration(block=FALSE)
    histos=fetch_histonames(params,params['db_select'])
#    tags=fetch_tagnames(params,params['db_select'])
    tags=params['tags'][params['db_select']]

    cursor = cursor_new(68 & 0xfe)
    page_box.get_window().set_cursor(cursor)
    histonames=histos.keys()
    tagnames=tags.keys()

    if len(histonames)>0:
      table.attach(GtkLabel("%d histogram(s) found in this database"%(len(histonames))),0,1,
      1, 2, yoptions=0, xpadding=5, xoptions=0)    
    elif len(tagnames)>0:
      table.attach(GtkLabel("%d container(s) found in this database"%(len(tagnames))),0,1,
      1, 2, yoptions=0, xpadding=5, xoptions=0)    
    else:
      table.attach(GtkLabel("No usable objects found in this database"),0,1,
      1, 2, yoptions=0, xpadding=5, xoptions=0)    
      vbox.show_all()
      next.set_sensitive(FALSE)
      return 
    

  table.attach(GtkHSeparator(),0,2,2,3)    
  table.attach(GtkLabel("Put values in:"),0,2,
   3, 4, yoptions=0, xpadding=5, xoptions=0)      

  params['sheet_choice']=0
  button1 = GtkRadioButton(None, "Existing sheet:") 
#  menu=GtkOptionMenu()
  menu=GtkCombo()
  button1.connect("toggled",sheet_toggle,params,menu,0)
  sheets=sg.worksheet_names()
  menu.set_popdown_strings(sheets)
  menu.set_value_in_list(TRUE,FALSE)
  #menu.set_menu(create_menu(sheets))
  active=sg.active_worksheet_name()
  params['sheet_name']=active

  for i in range(len(sheets)):
    if active==sheets[i]:
      menu.entry.set_text(active)
      break
  menu.entry.set_editable(FALSE)
  menu.entry.connect("changed",sheet_combo_changed,params)

  hbox=GtkHBox()
  hbox.pack_start(button1,expand=FALSE,fill=FALSE,padding=0)
  hbox.pack_start(menu,expand=FALSE,fill=FALSE,padding=5)
  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)

  button2 = GtkRadioButton(button1, "New sheet named '"+params['db_select']+"'") 
  button2.connect("toggled",sheet_toggle,params,None,1)  
  hbox=GtkHBox()  
  hbox.pack_start(button2,expand=FALSE,fill=FALSE,padding=0)
  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)
 
  hbox=GtkHBox()
  button3 = GtkRadioButton(button1, "New sheet named: ") 

  sheet_entry=GtkEntry()
  sheet_entry.connect("changed",new_sheet_name_changed,params)
  hbox.pack_start(button3,expand=FALSE,fill=FALSE,padding=0)
  hbox.pack_start(sheet_entry,expand=TRUE,fill=TRUE,padding=5)

  vbox.pack_start(hbox,expand=TRUE,fill=TRUE,padding=5)
  sheet_entry.set_sensitive(FALSE)
  button3.set_active(FALSE)
  button3.connect("toggled",sheet_toggle,params,sheet_entry,2)

  vbox.show_all()
    


def unselect_hist(tree,item,item2,(params,dbname,histname)):
  params['obj_select_type']=''
  params['obj_select']=''
  params['db_select']=''
  params['hselect'][dbname][histname]=FALSE

def fetch_histonames(params,dbname):
    rpc_params={"bootfile":params["fdname"],
                "dbs":[dbname]}  
    histos=params['dbsvr'].DBServer.getHistos(rpc_params)

    types={}
    params['histos'][dbname]=types
    histos['names']={}
    names=histos['histonames']
    htypes=histos['histotypes']
    for i in range(len(names)):
      types[names[i]]=htypes[i]
    return types

def fetch_tagnames(params,dbname):
    rpc_params={"bootfile":params["fdname"],
                "dbs":[dbname]}  
    tags=params['dbsvr'].DBServer.getTags(rpc_params)
    tagnames=tags['tags']
    continfo={}
    for i in range(len(tags['tags'])):
        try:
            temp=continfo[tags['containertag'][i]]
        except:
          continfo[tags['containertag'][i]]={}
        rpc_params={"bootfile":params["fdname"],
                "db":dbname,
                "container":tags['containertag'][i],
                "tagname":tags['tags'][i]}
        print "fetching %s:%s"%(tags['containertag'][i],tags['tags'][i])          
        while events_pending():
          mainiteration(block=FALSE)        
        columns=params['dbsvr'].DBServer.getColumns(rpc_params)
        if columns:
          continfo[tags['containertag'][i]][tags['tags'][i]]=columns
      
    params['tags'][dbname]=continfo
    print continfo
    return continfo


def io_thread(params):
  params['histos']={}
  dbitems=params['dbitems'].keys()
  for i in range(len(dbitems)):
    dbname=dbitems[i]
    labelstring="http://"+params["host"]+":"+params["port"]+params["path"]+\
    "\n Scanning for histograms:\n"+dbname
    params['dblabel'].set_text(labelstring)
    rpc_params={"bootfile":params["fdname"],
                "dbs":[dbname]}
    
    while events_pending():
      mainiteration(block=FALSE)
    histos=params['dbsvr'].DBServer.getHistos(rpc_params)
    histonames=histos['histonames']
    histotypes=histos['histotypes']
    if len(histonames)>0:
       for j in range(len(histonames)):
         item=params["ctree"].insert_node(params['dbitems'][dbname],None,
                [histonames[j],histotypes[j]],expanded=TRUE,is_leaf=TRUE)

  labelstring="http://"+params["host"]+":"+params["port"]+params["path"]
  params['dblabel'].set_text(labelstring)



def connect(params):
  params["dbsvr"] = xmlrpclib.Server("http://"+params["host"]+":"+params["port"]+params["path"])
  dbs=params["dbsvr"].DBServer.getDBs(params["fdname"])
  params['dbs']=dbs

  params['dbitems']={}
  dbitems=params['dbitems']
  for i in range(len(dbs)):
    item=params["ctree"].insert_node(None,None,[dbs[i]],expanded=TRUE,is_leaf=FALSE)
    dbitems[dbs[i]]=item


def select_row_db(ctree,node,column,params):
  node_info=ctree.get_node_info(node)
  nodename=node_info[0]
  print node_info
  params['obj_select']=None
  params['obj_select_type']=None
  params['db_select']=None
  params['cont_select']=None
  params['tag_select']=None


# First check whether a histogram or tag was selected
  for db in params['dbitems'].keys():
      parent=params['dbitems'][db]
      params['db_select']=db
      params['obj_select']=''
      print "params['tags'].keys()=",params['tags'].keys()
      if parent==node:
	print "parent=",parent," node=",node
      if parent==node: # A database was selected
        print "Database selected!"
        params['db_select']=db
        params['obj_select']=None
	if params['histos'].has_key(db) or params['tags'].has_key(db):
	  break
        cursor = cursor_new(150 & 0xfe)
        ctree.get_window().set_cursor(cursor)
        while events_pending():
          mainiteration(block=FALSE)
        histos=fetch_histonames(params,node_info[0])
        histonames=histos.keys()
        params['histonodes'][db]=[]
        for i in range(len(histonames)):
          leaf=params["ctree"].insert_node(node,None,[histonames[i]],expanded=TRUE,is_leaf=TRUE)        
          params['histonodes'][db].append(leaf)

        #Fetch tags
        while events_pending():
          mainiteration(block=FALSE)
        containers=fetch_tagnames(params,node_info[0])
        contnames=containers.keys()
        params['tagnodes'][db]={}
        for i in range(len(contnames)):
          leaf=params["ctree"].insert_node(node,None,[contnames[i]],expanded=TRUE,is_leaf=FALSE)
#          params['tagnodes'][db][contnames[i]]=leaf
          tags=containers[contnames[i]]
          print tags
          tagnames=tags.keys()
#          tags['nodes']=[]
          for j in range(len(tagnames)):
            tleaf=params["ctree"].insert_node(leaf,None,[tagnames[j]],expanded=TRUE,is_leaf=FALSE)
#            tags['nodes'].append(tleaf)
            colnames=tags[tagnames[j]]['cols']

            for k in range(len(colnames)):
                cleaf=params["ctree"].insert_node(tleaf,None,[colnames[k]],expanded=TRUE,is_leaf=TRUE)
        while events_pending():
          mainiteration(block=FALSE)
        print "Setting cursor"
        cursor = cursor_new(68 & 0xfe)
        ctree.get_window().set_cursor(cursor)

        break
      elif ctree.is_ancestor(parent,node):
        if params['histos'][db].has_key(nodename):
            print "Histogram selected! ",nodename
            params['db_select']=db
            params['cont_select']=None
            params['tag_select']=None
            params['obj_select']=ctree.get_node_info(node)[0]
            params['obj_select_type']=params['histonodes'][db][ctree.get_node_info(node)[0]]
            break
        if params['tags'][db].has_key(nodename):
            print "Container selected! ",nodename
            params['db_select']=db
            params['cont_select']=nodename
            params['tag_select']=None
            params['obj_select']=ctree.get_node_info(node)[0]
            params['obj_select_type']="Container"
            break
        containers=params['tags'][db]
        contnames=containers.keys()
        tag_found=0
        col_found=0
        for name in contnames:
            if col_found:
                break
            if containers[name].has_key(nodename):
                print "Tag selected! ",nodename
                params['db_select']=db
                params['cont_select']=name
                params['tag_select']=nodename
                params['obj_select']=ctree.get_node_info(node)[0]
                params['obj_select_type']="Tag"
                tag_found=1
                break
            tags=containers[name]
            tag_names=tags.keys()
            for tname in tag_names:
                if nodename in tags[tname]['cols']:
                    print "Column selected! ",nodename
                    params['db_select']=db
                    params['cont_select']=name
                    params['tag_select']=nodename
                    params['obj_select']=ctree.get_node_info(node)[0]
                    params['obj_select_type']="Column"
                    col_found=1
                    break

        if tag_found or col_found:
            break

# This should never happen!
        print "Unknown object selected!"
        params['db_select']=''


def build_object_page(params,page_box,next=None,prev=None,cancel=None):
  vbox=GtkVBox()
  page_box.pack_start(vbox)
  vbox.set_homogeneous(FALSE)
  input=params['input']

  for name in ['host','path','port','fdname']:
     params[name]=input[name].entry.get_text()
     values=sg.config_get_value(name,"clarens")
     sg.config_set_value(name,"clarens",[params[name]]+
     filter(lambda x,y=params[name]: x != y,values),TRUE)
  sg.config_set_value("secure","clarens",input['secure'].get_active(),TRUE)

  params['histos']={}
  params['tags']={}
  params['histonodes']={}
  params['tagnodes']={}


  if input['secure'].get_active() and sys.version[0]>'1':
   protocol='https'
  else:
   protocol='http'
  labelstring=protocol+"://"+params["host"]+":"+params["port"]+params["path"]

  dblabel=GtkLabel(labelstring)
  params['dblabel']=dblabel
  vbox.pack_start(dblabel,expand=FALSE,fill=FALSE,padding=5)
  vbox.pack_start(GtkHSeparator(),expand=FALSE,fill=FALSE,padding=5)
  swin=GtkScrolledWindow()
  swin.set_policy(POLICY_NEVER,POLICY_NEVER)
  swin.show() 
  vbox.pack_start(swin,padding=5)


  ctree=GtkCTree(cols=1,titles=[params["fdname"]])
  ctree.set_expander_style(CTREE_EXPANDER_TRIANGLE)
  ctree.set_line_style(CTREE_LINES_DOTTED)
  ctree.connect("tree-select-row",select_row_db,params)
#  ctree.connect("tree-expand",expand_row_db,params)
  swin.add_with_viewport(ctree)

  params["ctree"]=ctree
  params['db_select']=''

  cursor = cursor_new(150 & 0xfe)
  page_box.get_window().set_cursor(cursor)
  while events_pending():
    mainiteration(block=FALSE)
  try:  
    connect(params)
  
  except socket.error, my_except:
    try: 
     errstring=my_except[1]
    except:
     errstring=my_except[0]
    swin.destroy()
    vbox.pack_start(GtkLabel("Unable to connect:\n"+errstring),
    expand=FALSE,fill=FALSE,padding=5)
    next.set_sensitive(FALSE)

  except xmlrpclib.ProtocolError, my_except:
    swin.destroy()
    vbox.pack_start(GtkLabel("XML-RPC error connecting to\n"+
     my_except.url+":\n"+my_except.errmsg),
    expand=FALSE,fill=FALSE,padding=5)
    next.set_sensitive(FALSE)
  except:
    swin.destroy()
    vbox.pack_start(GtkLabel("Unknown error\n"),
    expand=FALSE,fill=FALSE,padding=5)
    next.set_sensitive(FALSE)
    
  cursor = cursor_new(68 & 0xfe)
  page_box.get_window().set_cursor(cursor)


# Threads didn't quite work out...
#  mythread=threading.Thread(target=io_thread,args=[params])
#  print "starting thread"
#  params['threadname']=mythread.getName()
#  mythread.setDaemon(1)
#  mythread.start()
#  mythread.join()
#  print "after thread"
#  while events_pending():
#    mainiteration(block=FALSE)
  swin.set_policy(POLICY_NEVER,POLICY_AUTOMATIC)
  vbox.show_all()
#  idle_add(io_thread,(params))

  return vbox

def set_def_host():
    sg.config_set_value("host","clarens",["localhost"],FALSE)

def set_def_path():
    sg.config_set_value("path","clarens",["/cgi-bin/DBServer"],FALSE)

def set_def_port():
    sg.config_set_value("port","clarens",["80"],FALSE)

def set_def_fdname():
    sg.config_set_value("fdname","clarens",["/home2/myoofd/ORCATEST.boot"],FALSE)

def set_def_secure():
    sg.config_set_value("secure","clarens",FALSE,FALSE)
    
def commit_value():
    pass

def init_page(params,page_box,next=None,prev=None,cancel=None):
  connect_vbox=GtkVBox()
  page_box.pack_start(connect_vbox)
  frontpage=connect_vbox
  table = GtkTable(3, 2, FALSE)
  table.set_col_spacings(10)
  table.set_row_spacings(5) 
  connect_vbox.pack_start(table,expand=TRUE,fill=TRUE,padding=5)
  input=params["input"]

  input['host']=GtkCombo()
  input['host'].set_popdown_strings(sg.config_get_value("host","clarens"))
  input['path']=GtkCombo()
  input['path'].set_popdown_strings(sg.config_get_value("path","clarens"))
  input['port']=GtkCombo()
  input['port'].set_popdown_strings(sg.config_get_value("port","clarens"))
  input['fdname']=GtkCombo()
  input['fdname'].set_popdown_strings(sg.config_get_value("fdname","clarens"))

  names=['host','port','path','fdname']
  for i in range(len(names)):
    table.attach(GtkLabel(names[i]), 0, 1, i, i+1,yoptions=0,xpadding=5,xoptions=0)
    table.attach(input[names[i]], 1, 2,i,i+1,yoptions=0,xpadding=5,xoptions=EXPAND|FILL)

  input['host'].entry.set_text(sg.config_get_value("host","clarens")[0])
  input['path'].entry.set_text(sg.config_get_value("path","clarens")[0])
  input['port'].entry.set_text(sg.config_get_value("port","clarens")[0])
  input['fdname'].entry.set_text(sg.config_get_value("fdname","clarens")[0])

  input['secure'] = GtkCheckButton(label="Use SSL encryption")

  connect_vbox.add(GtkHSeparator())
  connect_vbox.add(input['secure'])
    
  input['secure'].set_active(sg.config_get_value("secure","clarens"))

  hbox=GtkHBox()
  connect_vbox.set_spacing(0)
  connect_vbox.show_all()
  return connect_vbox


def clarens_init():
  params={
#These are compulsory
  "funcs":[init_page,build_object_page,plot_sheet_page,plot_col_page,
           download_page],
  "finish":finish_func,

#This is optional
  "labels":["Connection","Object selection","Worksheet","Column","Download"],

#Some of the data we want to pass to out page constructor 
  "host":"localhost",
  "port":"80",
  "path":"/cgi-bin/DBServer",
  "fdname":"/home2/myoofd/ORCATEST.boot",
  "dbs":[],
  "dbsvr":0,
  "treepage":0,
  "frontpage":0,
  "tree_item":0,
  "db_label":"",
  "input": {'host': 0,
           'path': 0,
           'port': 0,
           'fdname': 0}
  }

  sg.config_register("host","clarens",set_def_host,commit_value)
  sg.config_register("path","clarens",set_def_path,commit_value)
  sg.config_register("port","clarens",set_def_port,commit_value)
  sg.config_register("fdname","clarens",set_def_fdname,commit_value)
  sg.config_register("secure","clarens",set_def_secure,commit_value)
  wizard=sgagtk.SGwizard(params)
  
  
if not sg:
  wizard=sgagtk.SGwizard(params,tabs=TRUE,modal=FALSE,title="Clarens remote analysis client")
  mainloop()
else:
 sg.new_plugin_group("Worksheet:Import:");
 sg.register_plugin("CMS Objectivity database objects","Worksheet:Import:",clarens_init)

