##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#####################################################################################
##Return_CR_DbQuantities
##
##PURPOSE: 
##To extract the quantities from the CRHits_Decay database.  The database
##contains information about the charge lost after a cosmic ray hit 
##
##INPUTS:
##
##          DetStr          - 'H1RG-022','H2RG-32-147', or 'H4RG-10-007' 
##          ElecSt          - 'ASIC' or 'LEACH'
##          DatabaseName    - 'CRHits_Decay'
##          Temp: int       - The temperature at which the darks were taken
##                         
##          SlopeFiles      - A string array containing the paths to the slope
##                            files reduced from the saturation exposures
##          FileLists       - A string array containing the paths to the dark
##                            exposures taken after saturation
##          QueryString     - The identifier for the rows that are sought.
##                            Should be a string with the form:
##                               "WHERE " + Qualifiers + " "
##                            if MODE == 1, QueryString == FILE_PIXID
##          PIXID           - The pixel ID key in the database.  This will be used
##                            in mode 1 to obtain one specific pixel
##          Verbosity: int
##                            0 - don't print much
##                            1 - print the values
##          MODE: int
##                            0 - Search through individual events
##                            1 - Go through gobal events and get minima and maxima
##                            2 - Search Single Table for Muons that are very large
##                                then return COSID to use with Mode=3
##                            3 - Search through table with single pixel details
##                                for all pixels in the event and return quantities.=                                
##          DBKeyStr: str   - An additional string to identify a renamed database
##                            e.g. _'4_10_09'
##
##EXAMPLES:
##CosIDs, CosEneDeps, QLosts, QRises=Return_CR_DbQuantities('H1RG-022', 'LEACH', '', 0)

###########################################################################
import MySQLdb
import pdb
import time
from HxRG_Class import *
from numpy import *
from pylab import *

def Return_CR_DbQuantities(DetStr, ElecStr, QueryString, Mode=0, \
                           TvFlag=0, Verbosity=0,\
                           ThisFilter='Blank', Temp=160, MinReadAC=50,\
                           MaxReadAC=20, CosRead=10, \
                           DBKeyStr='') :

  #Get the HxRG instance
  HxRG = HxRG_C(DetStr=DetStr, ElecStr=ElecStr, Filter=ThisFilter)

  #Only one Database at the moment
  DataBaseName = 'CRHit_Decays'
  SingleTableName  = HxRG.DetStrMySQL+'_'+HxRG.ElecStr+'_Sin_CRHits'+DBKeyStr
  GlobalTableName  = HxRG.DetStrMySQL+'_'+HxRG.ElecStr+'_Glo_CRHits'+DBKeyStr

  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()

  if Mode == 0:
    Query = "SELECT COSID, COSENEDEP, QLOST, QRISE, FIT_TAU FROM "+ SingleTableName+\
             " WHERE MAXREADAC < "+str(MaxReadAC)+ \
             " AND MINREADAC > " + str(MinReadAC)+ \
             " AND COSREAD < " + str(CosRead)+\
             " AND TEMP="+str(Temp) + QueryString+";"
    print 'Your query string is :'
    print '----------------------'
    print Query
    print '----------------------'
    conn.query(Query)
    Res        = conn.store_result()
    Rows       = Res.fetch_row(maxrows=0, how=1)
    NumRows    = Res.num_rows() 
    CosIDs     = zeros(NumRows,dtype=chararray)
    CosEneDeps = zeros(NumRows,dtype=float32)
    QLosts     = zeros(NumRows,dtype=float32)
    QRises     = zeros(NumRows,dtype=float32)
    Fit_Taus   = zeros(NumRows,dtype=float32) 
    #Get values from primary table and then access Dark table for each Pixel
    for RowNum in arange(NumRows):
      CosIDs[RowNum]     = Rows[RowNum]['COSID']
      CosEneDeps[RowNum] = Rows[RowNum]['COSENEDEP']
      QLosts[RowNum]     = Rows[RowNum]['QLOST']
      QRises[RowNum]     = Rows[RowNum]['QRISE']
      Fit_Taus[RowNum]   = Rows[RowNum]['FIT_TAU']
    return CosIDs, CosEneDeps, QLosts, QRises, Fit_Taus

  elif Mode == 1:
    Query = "SELECT MAXCOSEDEP, MAXQLOST, MAXQRISE, TOTCOSEDEP, TOTQLOST, TOTQRISE FROM "+ GlobalTableName+\
             " WHERE TEMP="+str(Temp) + QueryString+";"
    print 'Your query string is :'
    print '----------------------'
    print Query
    print '----------------------'

    conn.query(Query)
    Res         = conn.store_result()
    Rows        = Res.fetch_row(maxrows=0, how=1)
    NumRows     = Res.num_rows()
    MaxCosEDeps = zeros(NumRows,dtype=float32)
    MaxQLosts   = zeros(NumRows,dtype=float32)
    MaxQRises   = zeros(NumRows,dtype=float32)
    TotCosEDeps = zeros(NumRows,dtype=float32)
    TotQLosts   = zeros(NumRows,dtype=float32)
    TotQRises   = zeros(NumRows,dtype=float32)
    #Get values from primary table and then access Dark table for each Pixel
    for RowNum in arange(NumRows):
      MaxCosEDeps[RowNum]   = Rows[RowNum]['MAXCOSEDEP']
      MaxQLosts[RowNum]     = Rows[RowNum]['MAXQLOST']
      MaxQRises[RowNum]     = Rows[RowNum]['MAXQRISE']
      TotCosEDeps[RowNum]   = Rows[RowNum]['TOTCOSEDEP']
      TotQLosts[RowNum]     = Rows[RowNum]['TOTQLOST']
      TotQRises[RowNum]     = Rows[RowNum]['TOTQRISE']
    return MaxCosEDeps, MaxQLosts, MaxQRises, TotCosEDeps, TotQLosts, TotQRises
 
  elif Mode == 2:

    Query = "SELECT COSID, MAXCOSEDEP, MAXQLOST, MAXQRISE, TOTCOSEDEP, TOTQLOST, TOTQRISE FROM "+ GlobalTableName+\
             " WHERE round(TEMP)="+str(Temp) + QueryString+";"
    print 'Your query string is :'
    print '----------------------'
    print Query
    print '----------------------'

    conn.query(Query)
    Res         = conn.store_result()
    Rows        = Res.fetch_row(maxrows=0, how=1)
    NumRows     = Res.num_rows()
    CosIDs      = zeros(NumRows,dtype=chararray)
    MaxCosEDeps = zeros(NumRows,dtype=float32)
    MaxQLosts   = zeros(NumRows,dtype=float32)
    MaxQRises   = zeros(NumRows,dtype=float32)
    TotCosEDeps = zeros(NumRows,dtype=float32)
    TotQLosts   = zeros(NumRows,dtype=float32)
    TotQRises   = zeros(NumRows,dtype=float32)

    #Get values from primary table and then access Dark table for each Pixel
    for RowNum in arange(NumRows):
      CosIDs[RowNum]        = Rows[RowNum]['COSID']
      MaxCosEDeps[RowNum]   = Rows[RowNum]['MAXCOSEDEP']
      MaxQLosts[RowNum]     = Rows[RowNum]['MAXQLOST']
      MaxQRises[RowNum]     = Rows[RowNum]['MAXQRISE']
      TotCosEDeps[RowNum]   = Rows[RowNum]['TOTCOSEDEP']
      TotQLosts[RowNum]     = Rows[RowNum]['TOTQLOST']
      TotQRises[RowNum]     = Rows[RowNum]['TOTQRISE']

    return CosIDs, MaxCosEDeps, MaxQLosts, MaxQRises, TotCosEDeps, TotQLosts, TotQRises

  elif Mode == 3:

    Query = "SELECT COSREAD, COSENEDEP, QLOST, QRISE, DEPTH, MAXDARK FROM "+ SingleTableName+\
            " WHERE round(TEMP)="+str(Temp) + QueryString+";"
    print 'Your query string is :'
    print '----------------------'
    print Query
    print '----------------------'

    conn.query(Query)
    Res         = conn.store_result()
    Rows        = Res.fetch_row(maxrows=0, how=1)
    NumRows     = Res.num_rows()
    CosReads    = zeros(NumRows,dtype=float32)
    CosEDeps    = zeros(NumRows,dtype=float32)
    QLosts      = zeros(NumRows,dtype=float32)
    QRises      = zeros(NumRows,dtype=float32)
    Depths      = zeros(NumRows,dtype=float32)
    MaxDarks    = zeros(NumRows,dtype=float32)

    #Get values from primary table and then access Dark table for each Pixel
    for RowNum in arange(NumRows):
      CosReads[RowNum]   = Rows[RowNum]['COSREAD']
      CosEDeps[RowNum]   = Rows[RowNum]['COSENEDEP']
      QLosts[RowNum]     = Rows[RowNum]['QLOST']
      QRises[RowNum]     = Rows[RowNum]['QRISE']
      Depths[RowNum]     = Rows[RowNum]['DEPTH']
      MaxDarks[RowNum]   = Rows[RowNum]['MAXDARK']

    return CosReads, CosEDeps, QLosts, QRises, Depths, MaxDarks
  return 1
