#!/usr/bin/env python
import sys
import os
import operator
import string
import sqlite3
from . import mle_macro
from . import mle_macrostate
from . import mle_macrodevice


__all__ = ['MpsLogic']


class MpsLogic(object):
    """MPS Logic class"""
        
    def __init__(self, filename=None):
        self.filename = filename
        self.macro = {}
        self.macro_state = list()


    def init_with_cursor(self, cursor=None):
        # Make a list of Macro objects
        query = "select * from macro"
        cursor.execute(query)
        for row in cursor:
            tmp = mle_macro.Macro(
                is_active   = row['is_active'],
                is_code     = row['is_code'],
                name        = row['name'],
                description = row['description'],
                code        = row['code'],
                number      = row['macro_number'],
                primary_key = row['pk'])
            self.macro[tmp.primary_key] = tmp
        
        
        # Add a list of MacroState objects for each Macro
        query = "select * from macro_state where macro_fk = ? order by state_number"
        for macro_primary_key, macro in self.macro.iteritems():
            cursor.execute(query, (macro.primary_key,))
            for row in cursor:
                tmp = mle_macrostate.MacroState(
                    is_default                = row['is_default'],
                    name                      = row['name'],
                    number                    = row['state_number'],
                    solution                  = row['solution'],
                    rate_pockels_cell         = row['rate_enum_pc'],
                    rate_mechanical_shutter   = row['rate_enum_ms'],
                    rate_bykik                = row['rate_enum_bykik'],
                    rate_laser_heater_shutter = row['rate_enum_lhs'],
                    macro_parent              = macro)
                macro.state.append(tmp)
                self.macro_state.append(tmp)
        
    
        # Add a list of MacroInput objects for each macro
        query = "select * from macro_device where macro_fk = ? order by position"
        for macro_primary_key, macro in self.macro.iteritems():
            cursor.execute(query, (macro.primary_key,))
            for row in cursor:
                tmp = mle_macrodevice.MacroDevice(
                    name = row['device_name'],
                    position = row['position'])
                macro.device.append(tmp)
        
        
        # Add a list of "ignored when" and "ignores" Macros objects for each Macro
        self.macro_ignore = list()
        query = "select * from macro_ignore where macro_fk = ? order by macro_fk, ignored_when_macro_fk"
        for macro_primary_key, macro in self.macro.iteritems():
            cursor.execute(query, (macro.primary_key,))
            for row in cursor:
                ignorer = self.macro[row['ignored_when_macro_fk']]
                if ignorer is None:
                    continue
                
                macro.ignored_when.append(ignorer)
                ignorer.ignores.append(macro)
    
        return self




    def init_with_sqlite3_file(self, filename=None):
        # Connect to database
        connection             = sqlite3.connect(filename)
        connection.row_factory = sqlite3.Row
        cursor                 = connection.cursor()
        
        # Initialize with cursor
        self.init_with_cursor(cursor)
        
        # Set the file path so the database can be dumped
        self.filename = filename
        
        # Close connection to database
        connection.close()
        
        
        
        
    
    def __str__(self):
        str_list = []
        for macro_primary_key, macro in self.macro.iteritems():
            str_list.append(macro.name + "\n")
        return ''.join(str_list)
    
    
    
    
    
    def sorted_macro_list(self, attribute='name'):
        macro_list = self.macro.values()
        macro_list.sort(key=operator.attrgetter(attribute))
        return macro_list        
    
    
    
    
    
    def export_c_code(self, output_path=None, verbose=False):
        if verbose:
            print "Exporting mapping file to", output_path
        
        try:
            outfile = open(output_path, "w")
        except IOError, e:
            sys.stderr.write('Could not open "' + output_path + '": ' + e.strerror + "\n")
            return 1
        
        # Export all the "ignored when" macros first
        ignore_when_section = None
        section_template = string.Template("""
/*
 * Logic Ignored When $ignore_comment
 */

if ($ignore_test)
{""")

        print >> outfile, """
/* Initialize Max Rates to 120 Hz */
setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDevicePockelsCell);
setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceMechanicalShutter);
setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceBykik);
setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceFuture);
"""

        macro_ignore_code_list = list()
        macro_evaluation_code_list = list()
        for macro in self.sorted_macro_list("ignored_when_hash"):
            # Skip macros that are always used (not ignored), not active, or have no devices
            if (not macro.ignored_when) or (not macro.is_active) or (not macro.device):
                continue

            # If this is a new ignore when group, write the masking logic
            if ignore_when_section != macro.ignored_when_hash:                
                if ignore_when_section:
                    # There is an open section, print the code
                    print >> outfile, '\n\n'.join(macro_ignore_code_list)
                    print >> outfile, '}\nelse\n{'
                    print >> outfile, '\n\n'.join(macro_evaluation_code_list)
                    print >> outfile, "}"
                    macro_ignore_code_list = list()
                    macro_evaluation_code_list = list()

                ignore_when_section = macro.ignored_when_hash

                # Make a list of all the ignored when macros
                test_conjunction = ' || '
                comment_conjunction = ' or '
                ignore_test_list = list()
                ignore_test_comment = list()
                for ignore_macro in macro.ignored_when:
                    ignore_test_list.append(ignore_macro.ignore_test_c_code)
                    ignore_test_comment.append(ignore_macro.name)
                
                ignore_test = test_conjunction.join(ignore_test_list)
                ignore_comment = comment_conjunction.join(ignore_test_comment)
                                
                # Print the section header to the file
                print >> outfile, section_template.substitute(ignore_comment=ignore_comment, ignore_test=ignore_test)
                
            macro_ignore_code_list.append(macro.get_ignore_c_code(4))
            macro_evaluation_code_list.append(macro.get_c_code(4))
        
        if ignore_when_section:
            # There is an open section, print the code
            print >> outfile, '\n\n'.join(macro_ignore_code_list)
            print >> outfile, '}\nelse\n{'
            print >> outfile, '\n\n'.join(macro_evaluation_code_list)
            print >> outfile, "}"
            
        # Then export the macros that are always evaluated       
        print >> outfile, '\n\n\n/*\n * Always Evaluated\n */\n\n\n'
        for macro in self.sorted_macro_list("name"):
            # Skip macros that are sometimes ignored, not active, have no devices, or ignore other macros
            if macro.ignored_when or not macro.is_active or not macro.device or macro.ignores:
                continue
                                
            print >> outfile, macro.get_c_code()
                
        # Finally, export the macros that ignore others       
        print >> outfile, '\n\n\n/*\n * Determine if the truth tables are in states that will ignore other tables\n */\n'
        for macro in self.sorted_macro_list("name"):
            # Skip macros that are not active, have no devices, or don't ignore other macros
            if not macro.is_active or not macro.device or not macro.ignores:
                continue

            print >> outfile, macro.is_ignoring_c_code
                                
        
        
        
        outfile.close()
    
    
    
    
    def export_dump(self, output_path=None, verbose=False):
        if verbose:
            print "Exporting dump file to", output_path
        
        try:
            outfile = open(output_path, 'w')
        except IOError, e:
            sys.stderr.write('Could not open "' + output_path + '": ' + e.strerror + '\n')
            return 1
    
        os.popen('echo \'.dump\' | sqlite3 %r > %r ' % (self.filename, output_path))

    
    
    
    
    def export_latex(self, output_path=None, verbose=False):
        if verbose:
            print "Exporting LaTeX to", output_path
        
        try:
            outfile = open(output_path, "w")
        except IOError, e:
            sys.stderr.write('Could not open "' + output_path + '": ' + e.strerror + "\n")
            return 1
            
        # Write the latex header
        print >> outfile, """\\documentclass[10pt, oneside]{article}
\\usepackage{lcls-article}
\\usepackage[usenames]{color}
\\usepackage{listings}

\\definecolor{CommentColor}{rgb}{0,0.5,0.1}
\\definecolor{BgColor}{rgb}{1,1,0.93}

\\newcommand\\code{\\begingroup \\urlstyle{tt}\\Url}
%\\renewcommand\\revnum{A}

\\title{MPS Logic}

\\begin{document}

\\maketitle

\\lstset{language=C,frame=single,stringstyle=\\ttfamily,commentstyle=\\color{CommentColor},breaklines=true,morekeywords={state},frameround=tttt,backgroundcolor=\\color{BgColor}}
"""

        section_template = string.Template("""\n\\section{$section}\n\n""")

        # Export all the "ignored when" macros first
        ignore_when_section = None
        for macro in self.sorted_macro_list("ignored_when_hash"):
            # Skip macros that are always used (not ignored), not active, or have no devices
            if (not macro.ignored_when) or (not macro.is_active) or (not macro.device):
                continue

            # If this is a new ignore when group, write a subsection header
            if ignore_when_section != macro.ignored_when_hash:
                ignore_when_section = macro.ignored_when_hash

                # Make a list of all the ignored when macros
                conjunction = " or "
                ignore_list = list()
                for ignore_macro in macro.ignored_when:
                    ignore_list.append(ignore_macro.name)
                
                ignore = conjunction.join(ignore_list)
                                
                # Print the section header to the file
                print >> outfile, section_template.substitute(section='Ignored When ' + ignore)
                
            print >> outfile, macro.get_latex_table()
        
        # Then export the macros that are always evaluated       
        print >> outfile, section_template.substitute(section='Always Evaluated')
        for macro in self.sorted_macro_list("name"):
            # Skip macros that are sometimes ignored, not active, or have no devices
            if (macro.ignored_when) or (not macro.is_active) or (not macro.device):
                continue
                                
            print >> outfile, macro.get_latex_table()
        
        # Print the footer
        print >> outfile, "\\end{document}"
        
        outfile.close()

        
        
        
        
        
        
        

def main():
    # Test code
    pass

if __name__ == "__main__":
    main()

