# L-23 MCS 275 Fri 7 Mar 2008 : guidb2.py

# this GUI is to modify records to OurPyFiles

from Tkinter import *
import MySQLdb

class GUIdb():
   """
   a GUI to change records in our database
   """
   def __init__(self,wdw):
      """
      The records are displayed in listboxes.
      Buttons allow to connect, retrieve, and
      browse forward and backward.
      Radiobuttons set sorting preferences.
      A message label displays status info.
      """
      wdw.title("GUI to OurPyFiles db")
      self.message = StringVar()
      self.message.set("welcome to our database")
      self.messageLabel = Label(wdw, \
         textvariable = self.message)
      self.messageLabel.grid(row=0,column=0,columnspan=4)
      self.bc = Button(wdw, text='connect', \
         command = self.connect)
      self.bc.grid(row=1,column=0)
      self.lb = Label(wdw, text='give key :')
      self.lb.grid(row=1,column=1)
      self.ky = Entry(wdw,width=5)
      self.ky.grid(row=1,column=2)
      self.br = Button(wdw, text='retrieve', \
         command = self.retrieve)
      self.br.grid(row=1,column=3)
      self.tp = Entry(wdw,width=3)
      self.tp.grid(row=2,column=0)
      self.dt = Entry(wdw,width=10)
      self.dt.grid(row=2,column=1)
      self.nm = Entry(wdw,width=15)
      self.nm.grid(row=2,column=2,columnspan=2)
      self.cursor = 0

   def connect(self):
      """
      Connects to the database OurPyFiles.
      """
      try:
         db = MySQLdb.connect(db="OurPyFiles")
         self.message.set("connected to \"OurPyFiles\"")
         self.cursor = db.cursor()
      except:
         self.message.set("failed to connect to \"OurPyFiles\"")

   def query(self,key):
      """
      Returns the query for all the information
      of the script with the given key.
      """ 
      q = 'select typedate.t, n, d, f ' + \
          'from typedate, filedata ' + \
          'where filedata.t = typedate.i ' + \
          'and filedata.i = %d' % key
      return q

   def display(self,R):
      """
      Displays the result of the query.
      """
      tp = R[0] + '-' + str(int(R[1]))
      self.tp.delete(0,END)
      self.tp.insert(INSERT,tp)
      self.dt.delete(0,END)
      self.dt.insert(INSERT,R[2])
      self.nm.delete(0,END)
      self.nm.insert(INSERT,R[3])

   def retrieve(self):
      """
      Retrieves all records from the scripts table.
      """
      if self.cursor == 0:
         self.message.set("please connect first")
      else:
         key = int(self.ky.get())
         m = 'retrieving key %d' % key
         self.message.set(m)
         q = self.query(key)
         lc = self.cursor.execute(q)
         m = 'retrieved record %d' % key
         self.message.set(m)
         R = self.cursor.fetchall()
         self.display(R[0])

def main():
   top = Tk()
   show = GUIdb(top)
   top.mainloop()

if __name__ == "__main__": main()
