"""
For a given block visit, calculate the slew time, acquisition time, and science time based on
data in the SDB
"""
import sys 
import time 
import datetime 
import string
import numpy as np

import mysql

def getnightinfo(sdb, obsdate):
    return sdb.select('NightInfo_Id', 'NightInfo', 'Date=%s' % obsdate)[0][0]


def blockvisitstats(sdb, obsdate, update=True):
   """Determine the block visit statistics for an observation date.  These 
      statistics include slew time, acquisition time, and total science 
      time for the block.   For rejected blocks, this includes the time
      until the next pointing 

      Parameters
      ----------

      sdb: mysql-instance
           sdb is a connection to the science data base
      obsdate: string
           observation date of interest

   """
 
   #for a given obsdate get the night info
   nid=getnightinfo(sdb, obsdate)

   #get the times for the night
   record=sdb.select('EveningTwilightEnd, MorningTwilightStart', 'NightInfo', 'NightInfo_Id=%i' % nid)
   stime=record[0][0]
   etime=record[0][1]
   totaltime=(etime-stime).seconds
   #From the sdb, get the SoLogEvent table
   record=sdb.select('EventType_Id, EventTime', 'SoLogEvent', 'NightInfo_Id=%i' % nid)
   event_list=[]
   for i in range(len(record)):
       r=record[i]
       if r[1].seconds>43200:
          t=datetime.datetime(int(obsdate[0:4]), int(obsdate[4:6]), int(obsdate[6:8]), 0, 0, 0)+r[1]
       else:
          t=datetime.datetime(int(obsdate[0:4]), int(obsdate[4:6]), int(obsdate[6:8]), 0, 0, 0)+datetime.timedelta(days=1)+r[1]
       event_list.append([r[0], t])

   #sort the list by the datetimes
   event_list.sort(key=lambda e:e[1])

   #get the list of accepted blocks
   selcmd='BlockVisit_Id, Accepted, Proposal_Code, Block_Id'
   tabcmd='Block join BlockVisit using (Block_Id) join Proposal using (Proposal_Id) join ProposalCode using (ProposalCode_Id)'
   blocks=sdb.select(selcmd, tabcmd, 'NightInfo_Id=%i' % nid)
   blocks=list(blocks)
   #print blocks

   #list of accepted blocks
   pid_list=[]
   rej_list=[]
   for b in blocks: 
       if b[1]==1: 
          pid_list.append(b[2])
       else:
          rej_list.append(b[2])

   #print pid_list
   #print rej_list
       
   #get a list of all data from the night
   select_state='FileName, Proposal_Code, Target_Name, ExposureTime, UTSTART, h.INSTRUME, h.OBSMODE, h.DETMODE, h.CCDTYPE, NExposures, Block_Id'
   table_state='FileData  Join ProposalCode using (ProposalCode_Id) join FitsHeaderImage as h using (FileData_Id)'
   logic_state="FileName like '%"+obsdate+"%' order by FileName"
   img_list=sdb.select(select_state, table_state, logic_state)

   #now create a list of all pointing commands
   point_list=[]
   for r in event_list:
       if r[0]==3: point_list.append(r[1])

   #for b in blocks: if b[1]==3: blocks.remove(b)

   #now loop through that list and associate each pointing with a blocks
   block_list=[]
   blocks_orig = list(blocks)
   print blocks
   for point in point_list:
       starttime=point
       endtime=findnextpointing(starttime, event_list, etime)
       #now find any date sets that might be associated with this date and time
       #and the data and times 
       propcode, target, bid, instr, obsmode, detmode, exptime, nexposure = finddata(img_list, starttime, endtime)
       bvid = get_blockvisitfrompointtime(sdb, starttime, propcode)
       #print propcode, target, bid, instr, obsmode, detmode, exptime, nexposure
       #print starttime, endtime, propcode, target
       if propcode in pid_list and not (propcode in rej_list): 
           blocks = removepropcode(blocks, propcode)
           block_list.append([bvid, starttime, endtime, 0, propcode])