#! /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 = { 
        'sps-ichub21' : ( inice_filter, ( 21, ), 21 ),
        'sps-ichub29' : ( inice_filter, ( 29, ), 29 ),
        'sps-ichub30' : ( inice_filter, ( 30, ), 30 ),
        'sps-ichub38' : ( inice_filter, ( 38, ), 38 ),
        'sps-ichub39' : ( inice_filter, ( 39, ), 39 ),
        'sps-ichub40' : ( inice_filter, ( 40, ), 40 ),
        'sps-ichub49' : ( inice_filter, ( 49, ), 49 ),
        'sps-ichub50' : ( inice_filter, ( 50, ), 50 ),
        'sps-ichub59' : ( inice_filter, ( 59, ), 59 ),
        'sps-ithub01' : ( icetop_filter, ( 21, 29, 30, 38, 39, 40, 47, 58 ), 81 ),
        'sps-ithub02' : ( icetop_filter, ( 48, 49, 50, 57, 59, 66, 67, 74 ), 82 )
        }

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, 
        1, "SPS pedestal configuration", d
        )
    mkxml(hvpar, '%s-dark.xml' % hub, hub, hubid,
        2, "SPS dark noise configuration", d
        )
    mkxml(hvpar, '%s-lc.xml' % hub, hub, hubid,
        3, "SPS local coincidence configuration", d
        )

