##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
##Volcano_Extract_Database.py
##
##
##PURPOSE: 
##  To characterize the volcanos that are present in the H1RG and H2RG
##
##INPUTS: 
##      MODE:
## 
##KEYWORDS:
##	FileList: string      
##	    Optionally, all of the files to be examined can 
##	    be specified in this file, one per line
##	    1 - Plot quantities as script runs
##	TvPPT: int
##	    0 - Plot everything
##	    1 - Only plot the centroids
##	Verbosity: int
##	    0 - don't print much
##	    1 - print the values
##      UpdateDB: int
##          0 - don't update the database
##          1 - update the database
##      OverWrite: int
##          0 - don't overwrite the table
##          1 - overwrite the tables
##
##CALLING SEQUENCE:
##	VEB=Volcano_Extract_Database(QueryStr="FILTER = 'I' and VSUB !=-1")
## 
##EXAMPLES:
## 
##////////////////////////////////////////////////////////////////////////
##SETUP
execfile('/afs/slac/u/ki/lances/python/python_HxRG/HxRG_Setup.py')
execfile('/afs/slac/u/ki/lances/python/SPIEPlotSettings.py')
from HxRG_Class import *
from ReturnCentroid import *
from ReturnRadialAvg import *
from ReadCol import *
from Return_Persistence_Quantities import *
from Persistence_Get_Dark_Times import *
from DecayJacobian import *
from Linefit_func import *
import TableIO
import csv
import pdb
import time

def Volcano_Extract_Database(QueryStr='', DetStr='H1RG-022', ElecStr='ASIC',\
    FileList = '', XPix = 0, YPix = 0,\
    UpdateDB=1, OverWrite=0, Mode = 0, BatchMode = 0):

  ##GET THE PRELIMINARY DATA 
  HxRG = HxRG_C(DetStr=DetStr, ElecStr=ElecStr)
  DataBaseName = 'Volcanos'
  VolcanoTableName =HxRG.DetStrMySQL+'_'+ElecStr       

  try:
    conn=MySQLdb.connect (host="localhost",
                          user="root",
                          passwd="mysql",
                          db= DataBaseName,
                          unix_socket="/tmp/mysql.sock")
  except MySQLdb.Error, e:
        print "Error $d: $s" % (e.args[0],e.args[1])
        sys.exit
  cursor=conn.cursor()

  ##########################################################################################
  ## MODE 0 - CREATE THE DATABASE 
  ##########################################################################################
  if Mode == 0: 

    if QueryStr != '':
      Query = "SELECT PIXID, X, Y, TYPE, FR, SLOPE, VSUB, FILTER "+\
             " FROM " + VolcanoTableName +\
             " WHERE " + QueryStr+";"
    else:
      Query = "SELECT PIXID, X, Y, TYPE, FR, SLOPE, VSUB, FILTER "+\
             " FROM " + VolcanoTableName + ";"

    print 'Your query string is :'
    print '----------------------'
    print Query
    print '----------------------'
 
    conn.query(Query)
    VRes       = conn.store_result()
    VRows      = VRes.fetch_row(maxrows=0, how=1)
    NumVRows   = VRes.num_rows()
    PixIDs     = zeros(NumVRows,dtype=int32)
    XPixs      = zeros(NumVRows,dtype=int16)
    YPixs      = zeros(NumVRows,dtype=int16)
    Types      = zeros(NumVRows,dtype=int8)
    Slopes     = zeros(NumVRows,dtype=float32)
    FRs        = zeros(NumVRows,dtype=float32)
    VSUBs      = zeros(NumVRows,dtype=float32)
    Filters    = zeros(NumVRows,dtype=chararray)

    #Get values from primary table and then access Dark table for each Pixel
    for RowNum in arange(NumVRows):
      PixIDs[RowNum]    = VRows[RowNum]['PIXID']
      XPixs[RowNum]     = VRows[RowNum]['X']
      YPixs[RowNum]     = VRows[RowNum]['Y']
      Types[RowNum]     = VRows[RowNum]['TYPE']
      FRs[RowNum]       = VRows[RowNum]['FR']
      Slopes[RowNum]    = VRows[RowNum]['SLOPE']
      VSUBs[RowNum]     = VRows[RowNum]['VSUB']
      Filters[RowNum]   = VRows[RowNum]['FILTER']

    return PixIDs, XPixs, YPixs, Types, FRs, Slopes, VSUBs, Filters
 
