from collections import defaultdict
from datetime import datetime, timedelta

__all__ = ['transform']

def transform(aobvs, cobvs):
    cycle_convert, obvs, i = {}, {}, 1
    for row in aobvs.itervalues(): obvs[row['id']] = row

    while obvs != {}:
        min_dt = min([datetime(row['arryr'],row['arrmo'],row['arrda']) for row in obvs.itervalues()])
        cycnums = list(set([row['cycnum'] for row in obvs.itervalues() if datetime(row['arryr'],row['arrmo'],row['arrda']) == min_dt]))
        min_arrnames = [row['arrname'] for row in obvs.itervalues() if datetime(row['arryr'],row['arrmo'],row['arrda']) == min_dt and row['rapstate'].lower()=="ma"]
        
#        print str(i)
#        print str(obvs)
#        print str(cycnums)
#        print str(min_dt)
        
        for row in [row for row in obvs.itervalues()]:
            if datetime(row['arryr'],row['arrmo'],row['arrda']) == min_dt or row['cycnum'] in cycnums:
                cycle_convert[row['cycnum']] = i
                aobvs[row['id']]['cycle'] = i
                del(obvs[row['id']])   
            elif row['rapstate'].lower() == "ma":
                flag = False
                if datetime(row['arryr'],row['arrmo'],row['arrda']) <= (min_dt + timedelta(days=2)):             
                    for arrname in min_arrnames:
                        if arrname.find("PD") != -1 and row['arrname'].find("SD") != -1:
                            flag = True
                            break
                        elif arrname.find("SD") != -1 and row['arrname'].find("PD") != -1:
                            flag = True
                            break
                    if flag == True:
                        cycle_convert[row['cycnum']] = i
                        aobvs[row['id']]['cycle'] = i
                        cycnums.append(row['cycnum']) 
                        del(obvs[row['id']])    
        i += 1

    for row in cobvs.itervalues():
        try:
            cobvs[row['id']]['cycle'] = cycle_convert[row['cycnum']]
        except:
            print "Cycnum does not exist in arrest records for sentence record: "
            print str(cobvs[row['id']])
            
