from itertools import izip

from errors import *
from util import *

class AdmrecRules(object):
    """Class to handle coding of administration records (nonarr, noncrt, and nonprs)."""
    def __init__(self, log, segment, rulesets, rule_order):
        """
        @param log: Log object to use for log output.
        @param segment: The name of the current segment being processed (arrest, sentence, or prosecution).
        @param rulesets: A dictionary containing all the nonarr/noncrt state rulesets.
        @param rule_order: A dictionary (key is state abbr) of lists which contain the names of rulesets sorted in the order of rule priority
        """
        self.unknown = 2 if segment == 'arrest' else 3
        self.log = log
        self.segment = segment
        self.rulesets = rulesets
        self.rule_order = rule_order

    def convert_admrec(self, row, _index=0):
        """A global rule controller to convert the nonarr and noncrt variables.
        
        @param row: The current row to be converted
        @param _index: A variable to keep track of the recursive depth
        """
        
        state_key = get_state_key(row['%sstate' % self.segment[0]])
        
        if row['%schg' % self.segment[0]] == 998:
            return 1
        
        #get the current ruleset
        if state_key in self.rule_order:
            ruleset = self.rulesets[self.rule_order[state_key][_index]]
            #get the key
            key = '|'.join(ruleset.metadata.get_key(row))
            #increment index
            index = _index + 1
            if key_as_str(row['rapstatex']) == 'wvfbi': 
                key = key.replace('0', 'o')
            try:    
                #code noncrt or nonarr using key in ruleset
                return ruleset.convert(key)
                    
            except ConvertError:
                #check to see if we need to recurse 
                if index != len(self.rule_order[state_key]):
                    #dive down one layer
                    return self.convert_admrec(row, index)
                else:
                    return self.unknown
        
        #no rule for state
        else:
            return self.unknown