#! /bin/env python

import os, sys
from icecube.daq.domconfig import process_domcals, mkxml, db_connect, db_lookup_hvpar
import icecube.daq.domconfig

def reject_dom(d):
    dead = ( '29-59', '29-60', '30-23', '38-59', '50-36' )
    if d[3] in dead: return True
    return False
    
def inice_filter(d):
    return int(d[3][3:5]) <= 60
    
def icetop_filter(d):
    return int(d[3][3:5]) > 60
    
hubs = {
    'spts-ichub01' : ( inice_filter, (1, ), 21 ),
    'spts-ichub02' : ( inice_filter, (2, ), 29 ),
    'spts-ichub03' : ( inice_filter, (3, ), 30 )
    }

def load_doms(f):
    doms = list()
    while 1:
        s = f.readline()
        if len(s) == 0: return doms
        doms.append(s.split())
        

domlist = sys.argv.pop(1)
f = file(domlist)
f.readline()
doms = load_doms(f)

db_connect('fat-dbs.icecube.wisc.edu', 'penguin')

hvpar = dict()

for hub, strx in hubs.items():
    filt, strids, hubid = strx
    d = list()
    for dom in doms:
        if int(dom[3][0:2]) in strids and filt(dom) and not reject_dom(dom):
            mbid = dom[0]
            par = db_lookup_hvpar(mbid)
            if par is not None:
                hvpar[mbid] = par
            d.append(dom)
    
    print "Found", len(d), "DOMs on hub", hub
    mkxml(
        hvpar, '%s-pedestal.xml' % hub, hub, hubid, 
        4, "SPTS pedestal configuration", d
        )
    mkxml(hvpar, '%s-dark.xml' % hub, hub, hubid,
        5, "SPTS dark noise configuration", d
        )
    mkxml(hvpar, '%s-lc.xml' % hub, hub, hubid,
        6, "SPTS local coincidence configuration", d
        )

