from itertools import izip
import time

__all__ = ['get_records', 'get_select_meta']

def get_select_meta(orig_var_names):
    extra_vars = {'arrest':['arrest.%s' % v for v in ['achglit']] + ['arrestx.%s' % v for v in ['arrnamex', 'arrdatex', 'adispdatex', 'eventdate1x']],
                  'sentence':['sentencex.%s' % v for v in ['cstatnumx', 'cchglitx','crtcmtx', 'snttextx', 'eventdate1x', 'cdisptextx']]}
    
    #for debugging
#    extra_vars['arrest'].extend(['arrest.nonarr', 'arrestx.adisptextx'])
#    extra_vars['sentence'].extend(['sentence.noncrt'])
    
    select = {'arrest': ['arrest.%s' % v for v in orig_var_names['arrest']] + extra_vars['arrest'] +['arrest.nonarr'],
              'sentence': ['sentence.%s' % v for v in orig_var_names['sentence']] + extra_vars['sentence']+['sentence.noncrt']}
    
    select_str = {'arrest': ','.join(select['arrest']).replace('arrest.rapstate', 'arrestx.rapstatex'),
                  'sentence': ','.join(select['sentence']).replace('sentence.rapstate', 'sentencex.rapstatex')}
    
    select_str['sentence'] = select_str['sentence'].replace('sentence.crtname', 'sentencex.crtnamex')
        
    column_names = {'arrest': [s.replace('arrest.', '').replace('arrestx.', '') for s in select['arrest']],
                    'sentence': [s.replace('sentence.', '').replace('sentencex.', '') for s in select['sentence']]}
    
    return (select_str, column_names)

def get_records(seg_name, conn_cursor, **kw):
    try:
        #with closing(get_cnxn(kw['db_info']['name'],kw)) as cnx:
        #    with closing(cnx.cursor()) as c:
        conn_cursor.execute("""SELECT %s FROM %s
                     INNER JOIN %sx on %s.id = %sx.id
                     WHERE %s.casenum = %s""" % (
                    kw['select_str'][seg_name], seg_name, 
                    seg_name, seg_name, seg_name, 
                    seg_name, kw['id']))
        records = conn_cursor.fetchall()
        
        #create a dictionary of dictionaries: dict(id_of_record : dict( col_name : col_value for each column))
        #return dict((record['id'], record) for record in records)
        return dict([(record[0], dict([(c, r) for c,r in izip(kw['column_names'][seg_name], record)])) for record in records])
    except:
        kw['log'].write('ajuvenile', [seg_name, kw['id'], "Failed to extract casenum=%s" % kw['id']], store=True)
