from collections import defaultdict

__all__ = ['chgseq_transform', 'pjp_score', 'cdsp_score', 'chgsvr_score', 'chg_score']

def chgseq_transform(segment_abbr, observations):
    chgseq_var=''.join([segment_abbr,'chgseq'])
    chgsvr_var=''.join([segment_abbr,'chgsvr'])
    chg_var = ''.join([segment_abbr,'chg'])
    
    cycles = defaultdict(list)
    for row in observations.itervalues():
        cycles[row['cycle']].append(row)
    
    for cycle in cycles.keys():
        use_chgsvr = True
        for row in cycles[cycle]: 
            if row[chgsvr_var] not in [1, 2, 3, 4, 5, 6]: use_chgsvr = False
        for row in cycles[cycle]:  
            observations[row['id']]['score'] = 0
            if row.get(chgseq_var) == 998: observations[row['id']]['score'] += 999998
            else:
                if segment_abbr == 'c':
                    observations[row['id']]['score'] += pjp_score(row['pjp2'])
                    observations[row['id']]['score'] += cdsp_score(row['cdsp'],row['pjp2'])
                if use_chgsvr: observations[row['id']]['score'] += chgsvr_score(row[chgsvr_var])
                observations[row['id']]['score'] += chg_score(row[chg_var])
        _chgseq = 1
        for row in sorted(cycles[cycle], key=lambda k: k['score']):
            if row.get(chgseq_var) != 998: 
                observations[row['id']][chgseq_var] = _chgseq
                _chgseq += 1
                
    return observations
    
def pjp_score(_pjp):
    _pjp_codes = {1: 100000, 2: 200000, 3: 200000, 4: 400000, 5: 500000, 6: 500000, 7: 700000, 
                  8: 800000, 98: 800000, 99: 800000}   
    if _pjp in _pjp_codes.keys(): return _pjp_codes[_pjp]
    else: return 0
    
def cdsp_score(_cdsp,_pjp):
    if _pjp != 4: return 0
    elif _cdsp in [35, 36, 37, 38]: return 10000
    else: return 20000
    
def chgsvr_score(_chgsvr):
    if _chgsvr == 1: return 1000
    elif _chgsvr == 2: return 2000
    elif _chgsvr in [3, 4, 5, 6]: return 3000
    else: return 0

def chg_score(_chg):
    _chg_codes = [9, 10, 15, 20, 30, 13, 50, 110, 55, 70, 60, 78, 75, 90, 100, 95, 11, 120, 
                   140, 130, 135, 160, 145, 40, 170, 150, 180, 190, 230, 210, 240, 310, 250, 
                   220, 225, 260, 200, 280, 270, 290, 300, 320, 333, 330, 340, 345, 375, 360, 
                   350, 380, 385, 415, 400, 390, 420, 425, 445, 440, 430, 480, 570, 565, 560, 
                   460, 470, 625, 510, 665, 490, 500, 495, 673, 545, 530, 535, 620, 650, 640, 
                   600, 605, 630, 580, 610, 520, 555, 590, 660, 525, 540, 670, 550, 720, 680, 
                   681, 682, 683, 684, 685, 710, 715, 998, 999]
    score = 0
    for i in range(1,len(_chg_codes)+1):
        if _chg == _chg_codes[i-1]: score = i
    return score
        