#!/usr/bin/env python
import sys
import string
import re
from . import latex


__all__ = ['Macro']


class Macro(object):
    """MPS Logic macro class"""
    
    def __init__(self,
                 is_active   = True,
                 is_code     = False,
                 name        = None,
                 description = None,
                 code        = None,
                 number      = None,
                 primary_key = None):
        self.is_active    = is_active
        self.is_code      = is_code
        self.name         = name
        self.description  = description
        self.code         = code
        self.number       = number
        self.primary_key  = primary_key
        self.state        = list()
        self.device       = list()
        self.ignored_when = list()
        self.ignores      = list()


    # Primary Key Accessors
    def get_primary_key(self):
        return self._primary_key
    
    def set_primary_key(self, value):
        if value is None:
            self._primary_key = None
        else:
            self._primary_key = int(value)

    primary_key = property(get_primary_key, set_primary_key)
    

    # Is Active Accessors
    def get_is_active(self):
        return self._is_active

    def set_is_active(self, value):
        self._is_active = bool(value)

    is_active = property(get_is_active, set_is_active)


    # Is Code Accessors
    def get_is_code(self):
        return self._is_code

    def set_is_code(self, value):
        self._is_code = bool(value)

    is_code = property(get_is_code, set_is_code)


    def get_ignored_when_hash(self):
        self.ignored_when.sort()
        ignored_when_tuple = tuple(self.ignored_when)
        return hash(ignored_when_tuple)
        
    ignored_when_hash = property(get_ignored_when_hash)







    #------------------------------------------------------
    # C code values
    #------------------------------------------------------
    
    def get_ignore_c_code(self):
        ignore_state_number = self.state[0].number
        device_state_conditions = list()
        for device in self.device:
            operator = '' if ignore_state_number & (0x01 << device.position) else '!'
            device_state_conditions.insert(0, operator + device.name)            
        return ' && '.join(device_state_conditions)
    ignore_c_code = property(get_ignore_c_code)



    def get_c_code(self,indentation=0):
        rate_template = string.Template('    setMaxRateAfterDevice($rate, $device);\n')
        macro_code_list = list()
        macro_code_list.append(' ' * indentation + '/* ' + self.name + ' */\n')
        
        if self.is_code:
            beginning_of_line = re.compile('^', re.MULTILINE)
            macro_code_list.append('state = (unsigned int) -1; /* Initialize to an unlikely state number */\n')
            macro_code_list.append('{\n' + beginning_of_line.sub('    ', self.code) + '\n}\n')
            macro_code_list.append('switch(state)\n{\n')
            
            # Create the switch statement for the states
            for state in self.state:
                macro_code_list.append('    case %d:\n' % state.number)
                if state.is_default:
                    macro_code_list.append('    default:\n')
                    
                if state.rate_pockels_cell != -1:
                    macro_code_list.append('    ' + rate_template.substitute(
                        rate=state.c_code_rate_pockels_cell,
                        device="MPSMitigationDevicePockelsCell"))
                        
                if state.rate_mechanical_shutter != -1:
                    macro_code_list.append('    ' + rate_template.substitute(
                        rate=state.c_code_rate_mechanical_shutter,
                        device="MPSMitigationDeviceMechanicalShutter"))
                
                if state.rate_bykik != -1:
                    macro_code_list.append('    ' + rate_template.substitute(
                        rate=state.c_code_rate_bykik,
                        device="MPSMitigationDeviceBykik"))
                
                if state.rate_laser_heater_shutter != -1:
                    macro_code_list.append('    ' + rate_template.substitute(
                        rate=state.c_code_rate_laser_heater_shutter,
                        device="MPSMitigationDeviceFuture"))
                macro_code_list.append('        setMacroState(%d, %d);\n' % (self.number, state.number))
                macro_code_list.append('        break;\n')            
            macro_code_list.append('}\n')

        
        if not self.is_code:
            for state in self.state:
                state_device_conditions = list()
                ignore_state_number = state.number
                for device in self.device:
                    operator = ' ' if ignore_state_number & (0x01 << device.position) else '!'
                    state_device_conditions.insert(0, operator + device.name)
                macro_code_list.append('if (' + ' && '.join(state_device_conditions) + ')\n')
                    
                macro_code_list.append('{\n')
                if state.rate_pockels_cell != -1:
                    macro_code_list.append(rate_template.substitute(
                        rate=state.c_code_rate_pockels_cell,
                        device="MPSMitigationDevicePockelsCell"))
                        
                if state.rate_mechanical_shutter != -1:
                    macro_code_list.append(rate_template.substitute(
                        rate=state.c_code_rate_mechanical_shutter,
                        device="MPSMitigationDeviceMechanicalShutter"))
                
                if state.rate_bykik != -1:
                    macro_code_list.append(rate_template.substitute(
                        rate=state.c_code_rate_bykik,
                        device="MPSMitigationDeviceBykik"))
                
                if state.rate_laser_heater_shutter != -1:
                    macro_code_list.append(rate_template.substitute(
                        rate=state.c_code_rate_laser_heater_shutter,
                        device="MPSMitigationDeviceFuture"))
                macro_code_list.append('    setMacroState(%d, %d);\n' % (self.number, state.number))
                macro_code_list.append('}\n\n')
            
        return (' ' * indentation).join(macro_code_list)



    #------------------------------------------------------
    # LaTeX values
    #------------------------------------------------------
    
    def get_latex_name(self):
        return latex.escape(self.name)

    latex_name = property(get_latex_name)


    def get_devices_as_latex(self):
        conjunction = " & "
        device_list = list()
        for _device in self.device:
            device_list.insert(0, _device.latex_name)
            device_list.insert(0, conjunction)
            
        if device_list:
            device_list.pop(0)

        return ''.join(device_list)

    devices_as_latex = property(get_devices_as_latex)




    def get_many_device_latex_table(self):
        return "place holder"
    
    
    
    
    def get_code_latex_table(self):
        truth_table_header_template = string.Template("""
\\subsection{$name}
The following code assigns the truth table's state number to the \\texttt{unsigned int} variable \\texttt{state}.
\\begin{center}
\\begin{lstlisting}
$code
\\end{lstlisting}
\\end{center}


\\begin{center}
\\begin{tabular}{@{}lccccc@{}}
\\toprule
Name & Number & PC & MS & BYKIK & LHS \\\\
\\midrule
""")
        truth_table_rate_template = string.Template("$name & $number & $pc_rate & $ms_rate & $bykik_rate & $lhs_rate \\\\\n")

        truth_table_footer_template = string.Template("""
\\bottomrule
\\end{tabular}
\\end{center}
""")
        table_str = list()
        table_str.append(truth_table_header_template.substitute(name=self.latex_name, code=self.code))
        
        for state in self.state:
            table_str.append(truth_table_rate_template.substitute(
                name       = state.latex_name,
                number     = state.number,
                pc_rate    = state.latex_rate_pockels_cell,
                ms_rate    = state.latex_rate_mechanical_shutter,
                bykik_rate = state.latex_rate_bykik,
                lhs_rate   = state.latex_rate_laser_heater_shutter))
        
        table_str.append(truth_table_footer_template.substitute())
        return ''.join(table_str)
    


    def get_latex_table(self):
        if self.is_code:
            return self.get_code_latex_table()
        if len(self.device) > 2:
            # should use: return self.get_many_device_latex_table()
            pass
        
        truth_table_header_template = string.Template("""
\\subsection{$name}
\\begin{center}
\\begin{tabular}{@{}l${column_type}cccc@{}}
\\toprule
Name & $input_names & PC & MS & BYKIK & LHS \\\\
\\midrule
""")
        truth_table_rate_template = string.Template("$name & $numbers & $pc_rate & $ms_rate & $bykik_rate & $lhs_rate \\\\\n")

        truth_table_footer_template = string.Template("""
\\bottomrule
\\end{tabular}
\\end{center}
""")
        table_str = list()
        table_str.append(truth_table_header_template.substitute(
            name        = self.latex_name,
            column_type = "c" * len(self.device),
            input_names = self.devices_as_latex))
        
        number_of_devices = len(self.device)
        for state in self.state:
            table_str.append(truth_table_rate_template.substitute(
                name       = state.latex_name,
                numbers    = state.latex_number(number_of_devices),
                pc_rate    = state.latex_rate_pockels_cell,
                ms_rate    = state.latex_rate_mechanical_shutter,
                bykik_rate = state.latex_rate_bykik,
                lhs_rate   = state.latex_rate_laser_heater_shutter))
        
        table_str.append(truth_table_footer_template.substitute())
        return ''.join(table_str)








def main():
    # Test code
    macro = Macro()
    print macro
    del macro



    
if __name__ == "__main__":
    main()

