#! /usr/bin/env python
''' adcpsect.py
    Interface to retrieve db name & output path in order
    to run adcpsect_part2.py (the core program).

    Usage (NO required fields):
      adcpsect.py [-d 'adcpdb_2/a0000dir.blk'] [-o 'subdir'] OR
      adcpsect.py [--outdir 'subdir']

      Switches override defaults.
           -h    --help     : print this message and exit.
           -d    --dbpath   : relative path to database name, eg:
                            :   ../adcpdb/a0102 (includes dbname).
           -o    --outdir   : relative path to output directory. 
'''

import os, string, sys, os.path, glob, getopt
import FileDialog, tkMessageBox
from Tkinter import *

# Optional command line prelims________________
typed_dbpath = ''
typed_outdir = ''
inhtdocs = 0
def usage():
   print __doc__
   sys.exit()
try:
   options, args = getopt.getopt(sys.argv[1:], 'd:o:h:w',
                        ['dbpath=', 'outdir=', 'help', 'web'])
except getopt.GetoptError:
   usage()

for o, a in options:
   if o in ('-d', '--dbpath'):
      typed_dbpath = a
   elif o in ('-o', '--outdir'):
      typed_outdir = a
   elif o in ('-h', '--help'):
      usage()
   elif o in ('-w', '--web'):
      inhtdocs = 1

if (typed_outdir[-1:] == '/'):           #strip any trailing "/" 
   typed_outdir = typed_outdir[0:-1]
if inhtdocs == 0:   # absolute paths already if call from gweb
   if not typed_outdir == '':
      typed_outdir = os.path.join(os.getcwd(), typed_outdir)
   if not typed_dbpath == '':
         typed_dbpath = os.path.join(os.getcwd(), typed_dbpath)
#### end optionals ____________________________

mainwindow = Tk()
mainwindow.title('    ADCP Processing: Database Entry Form')
mainwindow.geometry('+300+200')


class Formdb:
    def __init__(self, master = None):
        self.master = master
        self.stopflag = 0
        self.f1 =  Frame(master, width = 450, height = 200, relief = RAISED, bd = 2)

        self.lblenter = Label(self.f1, text = 'Enter database name (Use *dir.blk):',
                                fg = 'dark blue',font = (('MS','Sans','Serif'),'14','bold'))
        self.dbname = StringVar()
        cpath = os.getcwd()
        cruiseID = cpath[len(cpath)-4:]
        dbpath = cpath + '/adcpdb/a' + cruiseID + 'dir.blk'              
        if os.path.isfile(dbpath):
           self.dbname.set(dbpath)
        else:
           dbpath = os.path.join(cpath, 'adcpdb')
           if os.path.exists(dbpath):
              self.dbname.set(dbpath)
              dbpathfn = dbpath + 'a' + cruiseID + 'dir.blk'
              if os.path.isfile(dbpathfn):
                 self.dbname.set(dbpathfn)           
           else:
              dbpath = cpath + '/*dir.blk'
              self.dbname.set(dbpath)           
        if os.path.exists(typed_dbpath):   # overwrite
            self.dbname.set(typed_dbpath)
        self.editdb = Entry(self.f1, textvariable = self.dbname,
                                width = 50, bg = 'white')
        self.btndb = Button(self.f1, text = '. . .', width = 1,
                                font = (('MS','Sans','Serif'),'9','bold'),
                                command = self.filefinddb, state = NORMAL)
        
        self.lbloutpath = Label(self.f1, text = 'Enter output path:',
                                fg = 'dark blue',font = (('MS','Sans','Serif'),'14','bold'))
        self.outp = StringVar()
        self.outp.set(os.getcwd())
        if os.path.exists(typed_outdir):
            self.outp.set(typed_outdir)
        self.editoutpath = Entry(self.f1, textvariable = self.outp,
                                width = 50, bg = 'white')
        self.btnoutp = Button(self.f1, text = '. . .', width = 1,
                                font = (('MS','Sans','Serif'),'9','bold'),
                                command = self.filefindop, state = NORMAL)
        
        self.btnOK = Button(self.f1, text = '   OK   ', command = self.btnOKed,fg = 'blue')
        self.btnCancel = Button(self.f1, text = 'Exit', command = self.f1.quit)

        ####___________________________________
        self.f1.pack()

        self.lblenter.place(relx = .5, rely = .15, anchor = CENTER)    
        self.editdb.place(relx = .87, rely = .28, anchor = E)
        self.btndb.place(relx = .87, rely = .28, anchor = W)
                          
        self.lbloutpath.place(relx = .5, rely = .5, anchor = CENTER)
        self.editoutpath.place(relx = .87, rely = .63, anchor = E)
        self.btnoutp.place(relx = .87, rely = .63, anchor = W)

        self.btnCancel.place(relx = .2, rely = .85, anchor = W)
        self.btnOK.place(relx = .8, rely = .85, anchor = E)
        ####___________________________________
           

    def filefinddb(self):
        x = 1
        while x == 1:
            findcnt = FileDialog.FileDialog(self.f1)
            findcnt.top.geometry('+300+200')
            cnt = findcnt.go(displayone.dbname.get(),'*dir.blk')
            # using /home/moli4/datasets/.. instead of pwd though less portable
            if cnt is None:
                print 'cancelled'
                x = 2
            else:
                self.dbname.set(cnt)
                if os.path.isfile(self.dbname.get()):
                    x = 2
                else:
                    tkMessageBox.showerror('Database file name','Incorrect DB File (path/name?)')

    def filefindop(self):
        x = 1
        while x == 1:
            findout = FileDialog.FileDialog(self.f1)
            findout.top.geometry('+300+200')
            cntop = findout.go()  #  using pwd 
            if cntop is None:
                print 'cancelled'
                x = 2
            else:
                self.outp.set(cntop)
                if os.path.isdir(cntop):
                    x = 2
                else:
                    tkMessageBox.showerror('Output path name','Invalid path, or = file')
           
    def filechk(self): # validate 
        if not os.path.isfile(displayone.dbname.get()):
            displayone.stopflag = 1
            tkMessageBox.showerror('Database file name','Incorrect DB File (path/name?)')

    def outpathchk(self): # validate
        if not os.path.isdir(displayone.outp.get()):
            displayone.stopflag = 1
            tkMessageBox.showerror('Output path name','Invalid path, or = file')
        lck = displayone.outp.get()
        if lck[-1:] == '/':
            lck = lck[:-1]
            displayone.outp.set(lck)

    def timechk(self): # validate
        if len(self.tr) < 10:
            display.stopflag = 1
            tkMessageBox.showerror('','Time range incorrect or not found')

    def establishtimes(self):
        dbdir, dbfn = os.path.split(self.dbname.get())
        dbshortfn = dbfn[0:-7]
        trdir = dbdir[0:-7]
        trfile = '%s/scan/%s.tr' %(trdir, dbshortfn)
        trfile2 = '%s/scan/*.tr' %(trdir)
        trfle = glob.glob(trfile2)
        if os.path.exists(trfile):  # first try to find *.tr file (much faster)
            trf = open(trfile, 'r')
            strlist = string.strip(trf.readline())
            #print 'timerange is<' + strlist + '>'
            trf.close()
            self.tr = '"' + strlist + '"'
            #self.tr = '%s%s%s%s' \
            #          %(strlist[0:10], strlist[11:19], \
            #            strlist[23:33], strlist[34:])
        elif os.path.exists(trfle[0]):  # still much faster
            trf = open(trfle[0], 'r')
            strlist = string.strip(trf.readline())
            #print 'timerange is<'+ strlist + '>'
            trf.close()
            self.tr = '"' + strlist + '"'
            #self.tr = '%s%s%s%s' \
            #          %(strlist[0:10], strlist[11:19], \
            #            strlist[23:33], strlist[34:])
        else:
            print 'THIS MAY TAKE A MINUTE !'
            db = '%s/%s' %(dbdir, dbshortfn)
            filen = '%s/g_prof.lst' %(self.outp.get())
            lstprof_cnt_str = '''
                dbname:             %(db)s
                output:             %(filen)s
                step_size:          1
                time_ranges:
                        all
                '''
            fname = '%s/g_lstprof.cnt' %(self.outp.get())
            lstpf = open(fname, 'w')    
            lstpf.write(lstprof_cnt_str % vars())
            lstpf.close()
            runstr = 'lst_prof %s' %(fname)
            os.system(runstr)
            lstout = open(filen, 'r')
            strlist = string.strip(lstout.readlines())
            #print 'timerange is<' + strlist + '>'
            lstout.close()
            os.remove(fname)
            os.remove(filen)
            endstr2 = strlist[-2] # chg. to reg. expression later ?
            begstr5 = strlist[5]
            self.tr = '"' + strlist + '"'
            #self.tr = '%s%s%s%s' \
            #          %(begstr5[0:10], begstr5[12:20], \
            #            endstr2[0:10], endstr2[12:20])
                       
    def btnOKed(self):
        displayone.stopflag = 0
        displayone.filechk()
        displayone.outpathchk()
        displayone.establishtimes()
        displayone.timechk()
        if not displayone.stopflag:
            mainwindow.withdraw()  
            sysstr = 'adcpsect_part2.py %s %s %s' %(displayone.dbname.get(),
                                                    displayone.outp.get(),
                                                    displayone.tr)
            os.system(sysstr)
            self.btnCancel.invoke()
                

displayone = Formdb(mainwindow)
#if __name__ ==  '__main__':
mainwindow.mainloop()
