
from ....util import key_as_str
from ....errors import ConvertError

def set_pjp2(sentence_records, ruleset, **kw):
    for row in sentence_records.itervalues():
        #Step 1: Create cdsp2.    (result-1=dism/acq/nol, 2=convict, 3=other, 98,99, -99)
        row['pjp2'] = None
        rapstate = row['rapstate'].lower()
        confine = -1
        confine2 = -1
        prb2 = -1
        '''Create 3 variables for below            
                if (incmax GT 0 and LT 99199100)    INCMAXSHORT=1    OTHERWISE    INCMAXSHORT=INCMAX
                if (suspmax GT 0 and LT 99199100)    SUSPMAXSHORT=1    OTHERWISE    SUSPMAXSHORT=SUSPMAX
                if (prb GT 0 and LT 99899899.88)    PRB2=1    OTHERWISE    PRB2=0'''
        if row['incmax'] is not None:
            incmax_short = 1 if 0 < row['incmax'] < 99199100 else round(row['incmax'],2)
        else:
            incmax_short = 0
        if row['suspmax'] is not None:
            suspmax_short = 1 if 0 < row['suspmax'] < 99199100 else round(row['suspmax'],2)
        else:
            suspmax_short = 0
        prb2 = 1 if 0 < row['prb'] < 99899899.88 else 0
        
        '''Identify exceptions
            NMexempt=1, if rapstate=NM and string in senttextx or crtcmtx="PARTIALLY SUSPENDED SENTENCE"
            NMexempt=0, if rapstate=NM and string in senttextx or crtcmtx NE "PARTIALLY SUSPENDED SENTENCE"
            
            NJexempt=1, if rapstate=NJ and sentextx string starts with "PARTIALLY SUSPENDED"
            NJexempt=0, if rapstate=NJ and sentextx string DOES NOT start with "PARTIALLY SUSPENDED"
            
            MNexempt=1, if rapstate=MN and string in senttextx ="PRONOUNCED"
            MNexempt=0, if rapstate=MN and string in senttextx NE "PRONOUNCED"'''
            
        exempt = {}
        if rapstate == 'nm':
            exempt['nm'] = 0
            
            for var in ('crtcmtx', 'snttextx'):
                if key_as_str(row[var]).find('partially suspended sentence') != -1:
                    exempt['nm'] = 1
             
        elif rapstate == 'nj':
            exempt['nj'] = 1 if key_as_str(row['snttextx']).startswith('partially suspended') else 0
        
        elif rapstate == 'mn':
            exempt['mn'] = 1 if key_as_str(row['snttextx']).find('pronounced') != -1 else 0
        try:
            cdsp2 = ruleset['pjp_1'].convert(row['cdsp'])
        except ConvertError:
            kw['log'].write('pjp2', [row['id'], row['cstate'], row['cdsp'], "Key not found in crosswalk pjp_1"], store=True)
            cdsp2 = 99
        
        #Step 2: Creation of pjp2 for dism and pjp cases.
        if cdsp2 == 1:
            row['pjp2'] = 7
        elif row['pjp'] not in [-99, -88]:
            row['pjp2'] = row['pjp']
#        elif row['pjp'] == 99:
#            row['pjp2'] = 9
        
        if rapstate == 'sc':
            if row['pjp2'] in [8, 98, 99] and cdsp2 == 2:
                row['pjp2'] = 6
    
        #Step 3: Create pjp2 for remaining cases.
        if row['pjp2'] is None:
            #Create a CONFINE variable to identify if case involved confinement:
            #handle all states
            if incmax_short == 0 and suspmax_short in (0, 1, 99799799.77, 99999999.99):
                confine = 0
            elif incmax_short == 1 and suspmax_short == 1:
                confine = 0 if row['incmax'] == row['suspmax'] else 1
            elif incmax_short == 1 and (suspmax_short in (0, 99899899.88, 99999999.99) or suspmax_short < 0):
                confine = 1
            elif incmax_short == 1 and suspmax_short == 99299299.22:
                confine = 1
            elif incmax_short in (99299299.22, 99399399.33) and suspmax_short in (99299299.22, 99799799.77):
                confine = 0
            elif incmax_short in (99299299.22, 99399399.33) and suspmax_short in (0, 1, 99899899.88, 99999999.99):
                confine = 1
            elif incmax_short == 99799799.77 and suspmax_short == 1:
                confine = 0
            elif incmax_short == 99799799.77 and suspmax_short in (0, 99899899.88, 99999999.99):
                confine = 1
            elif incmax_short == 99899899.88 and suspmax_short in (1, 99899899.88, 99999999.99):
                confine = 0
            elif incmax_short == 99999999.99 and suspmax_short in (0, 1, 99999999.99):
                confine = 0
            elif incmax_short in (99199199.11, 99399399.33, 99699699.66) and suspmax_short == 99999999.99:
                confine = 1
            elif (rapstate not in ('az', 'mt', 'mn') and not exempt.get('nj')) and incmax_short == 1 and suspmax_short == 99799799.77:
                confine = 0
            elif not exempt.get('nm') and incmax_short == 99999999.99 and suspmax_short == 99799799.77:
                confine = 0
            elif (not exempt.get('nj') and rapstate != 'wa') and incmax_short == 99799799.77 and suspmax_short == 99799799.77:
                confine = 0
            elif rapstate in ('az', 'mt', 'mn') and incmax_short == 1 and suspmax_short == 99799799.77:
                confine = 1
            elif exempt.get('nj') and incmax_short in (1, 99799799.77) and suspmax_short == 99799799.77:
                confine = 1
            elif exempt.get('nm') and incmax_short == 99999999.99 and suspmax_short == 99799799.77:
                confine = 1
            elif rapstate == 'wa' and incmax_short == 99799799.77 and suspmax_short == 99799799.77:
                confine = 1
                
            #Step C: Create confine2 - indicating type of confinement\
            cnf={1:1, 2:2, 3:3, 4:3, 6:3, 8:3, 9:3}
            if confine == 0:
                confine2 = 0
            elif confine == 1:
                try:
                    confine2 = cnf[row['cnf']]
                except KeyError as e:
                    kw['log'].write('pjp2', [row['id'], row['cstate'], row['cnf'], "CNF not found in {1:1, 2:2, 3:3, 4:3, 6:3, 8:3, 9:3} "], store=True) 
            else:
                kw['log'].write('pjp2', [row['id'], row['cstate'], confine, "Confine out of range (0,1)"], store=True)
                
            if row['id'] in [212207, 131421]:
                print '------------------------'
                print 'ID: %s' % str(row['id'])
                print 'cnf: %s' % str(row['cnf'])
                print 'confine: %s' % str(confine)
                print 'confine2: %s' % str(confine2)
                print 'pjp: %s' % str(row['pjp'])
                print 'pjp2: %s' % str(row['pjp2'])
                print 'cdsp: %s' % str(row['cdsp'])
                print 'cdsp2: %s' % str(cdsp2)
                print 'prb: %s' % str(row['prb'])
                print 'prb2: %s' % str(prb2)
                print 'incmax: %s' % str(row['incmax'])
                print 'incmax_short: %s' % str(incmax_short)
                print 'suspmax_short: %s' % str(suspmax_short)
                print '------------------------'
                
            #Step D: Use cdsp2,confine2,prb2 to code remaining pjp2.
            try:
                row['pjp2'] = ruleset['pjp_2'].convert('|'.join([str(cdsp2),str(confine2)]))
            except ConvertError:
                try:
                    row['pjp2'] = ruleset['pjp_3'].convert('|'.join([str(cdsp2), str(confine2), str(prb2)]))
                except ConvertError:
                    kw['log'].write('pjp2', [row['id'], row['cstate'], cdsp2, confine2, prb2, "Unable to find key combo on crosswalk"], store=True)
                    
            if row['pjp'] == -99:
                row['pjp2'] = 99
            
        #calculate jpmx
        if row['pjp2'] in (1,2,3):
            if incmax_short in (1, 99299299.22) and suspmax_short in (0, 99899899.88, 99999999.99):
                row['jpmx'] = row['incmax']
            elif incmax_short in (99199199.11, 99399399.33, 99699699.66, 99799799.77) and suspmax_short in (99899899.88, 99999999.99):
                row['jpmx'] = row['incmax']
            elif incmax_short == 99799799.77 and suspmax_short == 0:
                row['jpmx'] = row['incmax']    
            elif incmax_short == 1 and suspmax_short == 1:
                if round(row['incmax'],2) > round(row['suspmax'],2):
                    row['jpmx'] = row['incmax'] - row['suspmax']
                else:
                    row['jpmx'] = row['incmax']
            elif incmax_short == 1 and suspmax_short == 99299299.22:
                row['jpmx'] = 99799799.77
            elif incmax_short in (99299299.22, 99399399.33) and suspmax_short in (1, 99799799.77):
                row['jpmx'] = 99799799.77
            elif incmax_short == 1 and suspmax_short == 99799799.77:
                if rapstate == 'az' and confine == 1: 
                    row['jpmx'] = row['incmax']
                elif rapstate == 'mn' and not exempt.get('mn') and confine == 1:
                    row['jpmx'] = row['incmax']
                elif exempt.get('mn') or rapstate == 'mt' or exempt.get('nj'):
                    row['jpmx'] = 99799799.77
            elif incmax_short == 99799799.77 and suspmax_short == 99799799.77:
                if rapstate == 'wa' or exempt.get('nj'):
                    row['jpmx'] = 99799799.77
            elif incmax_short == 99999999.99 and suspmax_short == 99799799.77:
                if exempt.get('nm'):
                    row['jpmx'] = 99799799.77
            elif incmax_short == 1 and suspmax_short < 0:
                row['jpmx'] = row['incmax']
        else:
            if incmax_short < 0 and suspmax_short == 99999999.99:
                row['pjp2'] = 6
                row['jpmx'] = 99999999.99
        
        if row['pjp2'] in (4,5,7,8,98) and 'jpmx' not in row:
            row['jpmx'] = 99899899.88
        if row['pjp2'] in (6,99) and 'jpmx' not in row:
            row['jpmx'] = 99999999.99
        if row['pjp'] in (1,2,3) and 'jpmx' not in row:
            row['jpmx'] = 99799799.77
