#!/usr/bin/python

#from gtk import *
import dbGtk
import sys
import gtk
import string


default_join_rules=\
r"""%/%_%_id \3s/\3_id
tbl%/id% tbl\2s/id
%/%_%_id \3/id
%/%_%_id \2/\3_id
%/%_id \2/id
%_%/%_id \2/id
tbl%/id% tbl\2/\2id"""


class login_widget:
    #connection to the database
    db=None

    #strings
    thedbapi=None
    thehost="localhost"
    theuser=""
    thepasswd=""
    thedb=""

    field_entrywidget={}
    
    def __init__(self):
        #while db ==None:
        window=gtk.GtkWindow(gtk.WINDOW_TOPLEVEL)
        window.set_title("sql editor")
        v=gtk.GtkVBox()
        v.show()
        window.add(v)

        self.b1=gtk.GtkRadioButton(None,"MySQL")
        self.b1.show()
        v.pack_start(self.b1)
        self.b2=gtk.GtkRadioButton(self.b1,"PostgreSQL")
        self.b2.show()
        v.pack_start(self.b2)
        
        
        for i in [ 'host','user','passwd','db']:
            h=gtk.GtkHBox()
            v.pack_start(h)
            h.show()
            l=gtk.GtkLabel(i)
            l.show()
            h.pack_start(l)
            e=gtk.GtkEntry()
            e.show()
            if i == 'passwd':
                e.set_visibility(gtk.FALSE)
            h.pack_start(e)
            var=getattr(self, "the" + i)
            e.set_text(var)
            self.field_entrywidget[i]=e

        b=gtk.GtkButton("CONNECT")
        b.show()
        b.connect("clicked", self.dbconnect)
        v.pack_start(b)

        self.statusbar=s=gtk.GtkStatusbar()
        s.show()        
        v.pack_start(s)

        s.push(1,"""warning: this programs is very young\n\
do not edit valuable data with it""")

        window.connect("delete_event", gtk.mainquit)
        window.show()
        self.window=window
    def dbconnect(self,button):

        for i in [ 'host','user','passwd','db']:
            e=self.field_entrywidget[i]
            setattr(self, "the" + i, e.get_text())

        if self.b1.get_active():
            self.thedbapi="MySQLdb"
        else:
            self.thedbapi="PgSQL"
            
        (dbapi,dbapi_exceptions)=dbGtk.load_dbapi(self.thedbapi)


        try:
            if self.b1.get_active():
                #connect
                self.db = dbapi.connect(host=self.thehost, user=self.theuser,
                                        #THIS IS A MISTAKE in MySQLdb
                                          passwd=self.thepasswd)
            else:
                self.db = dbapi.connect(host=self.thehost, user=self.theuser,
                                        password=self.thepasswd)
            self.db.select_db(self.thedb)
        except dbapi_exceptions.Error, msg:
            self.statusbar.push(1,str(msg))
        except Exception, msg:
            self.statusbar.push(1,str(msg))
        else:
            gtk.mainquit()


login=login_widget()

gtk.mainloop()



login.window.destroy()


if login.db :
    (dbapi,dbapi_exceptions)=dbGtk.load_dbapi(login.thedbapi)

class table_browser:
    #tables infos
    #table_info={}
    #fields in tables
    table_fields={}
    
    def __init__(self,db,thedb):
        db.select_db(thedb)

        window=gtk.GtkWindow(gtk.WINDOW_TOPLEVEL)
        window.set_title("sql:/"+login.thedb)
        v=gtk.GtkVBox()
        v.show()
        window.add(v)

        c=db.cursor()        
        c.execute('SHOW TABLES')
        tables=[]
        t=c.fetchone()        
        while t:
            tables.append(t[0])
            t=c.fetchone()
        del c

        for t in tables:
            info=dbGtk.table_info(login.db, login.thedb, t)
            #self.table_info[t]=info
            self.table_fields[t]=info.fields
            
            h=gtk.GtkHBox()
            v.pack_start(h)
            h.show()

            
            b=gtk.GtkButton("Edit")
            b.table_name=t[0]
            b.show()
            b.connect('clicked',self.edit_table,t)
            h.pack_start(b,gtk.FALSE,gtk.FALSE,gtk.FALSE)
            
            l=gtk.GtkLabel(t)
            l.show()
            h.pack_start(l)
            
            
        #for joins
        h=gtk.GtkHBox()
        h.show()
        l=gtk.GtkLabel("Join rules:")
        l.show()
        h.pack_start(l)
        b=gtk.GtkButton("(help)")
        b.show()
        b.connect("clicked",self.help)
        h.pack_start(b)
        v.pack_start(h)

        self.entry_widget = e = gtk.GtkText()
        e.show()
        e.set_editable(gtk.TRUE)
        #self.entry_widget.delete_text(0, self.entry_widget.get_length())
        e.insert_defaults(default_join_rules)
        v.pack_start(e)

        window.connect("delete_event", gtk.mainquit)
        window.show()
        self.window=window

    def help(self,b):
        window=gtk.GtkWindow(gtk.WINDOW_TOPLEVEL)
        window.set_policy(gtk.FALSE, gtk.TRUE, gtk.FALSE)
        window.set_title("sql-editor join help")
        #window.connect("delete_event", window.destroy)
        e=gtk.GtkText()
        e.show()
        e.set_editable(gtk.TRUE)
        e.insert_defaults(dbGtk.joins.__doc__)
        #FIXME: this is ignored...
        #e.set_usize(180,180)
        window.add(e)
        window.set_usize(580,580)
        window.show()
    def edit_table(self,b,name):
        l=self.entry_widget.get_length()
        t=self.entry_widget.get_chars(0,l)
        join_rules=string.split(t,'\n')

        (dbapi,dbapi_exceptions)=dbGtk.load_dbapi(login.thedbapi)
        dbGtk.editor(login.db, login.thedb, name,
                     #api
                     dbapi,dbapi_exceptions,
                     #these are used for automatic joins
                     join_rules, self.table_fields
                     )

        


if login.db :
    browser=table_browser(login.db,login.thedb)
    gtk.mainloop()
