#!/usr/bin/env python
'''
Add ignore condition to truth table
'''

import sys
import os
import re
import json
import sqlite3
import argparse

def indent(string, amount=4):
    line_start = re.compile(r'^', re.MULTILINE)
    return re.sub(line_start, ' ' * amount, string)

class Mpl(object):
    def __init__(self, mpl_cursor):
        self.cursor = mpl_cursor
    
    def ignore_macros(self):
        '''
        Return a dictionary of ignore macros
        {'macro_name': macro_pk, ... }
        '''
        self.cursor.execute(
            '''
            select
                m.ZNAME name,
                i.Z_PK pk
            from
                ZIGNOREMACRO i inner join 
                ZMACRO       m on i.ZMACRO == m.Z_PK
            '''
        )
        return dict(self.cursor.fetchall())

class MplError(Exception):
    def __init__(self, err_str):
        self.err_str = err_str
    def __str__(self):
        return self.err_str

def table_zent_zopt(mpl_cursor, table):
    mpl_cursor.execute('select Z_ENT, Z_OPT from {0}'.format(table))
    return mpl_cursor.fetchone()

def verify_condition(mpl_cursor,ignore):
    mpl = Mpl(mpl_cursor)
    ignore_macros = mpl.ignore_macros()
    if ignore not in ignore_macros:
      raise MplError('Unknown ignore condition "{0}" for {1}'.format(ignore, tt))

def apply_condition(mpl_cursor, truth_tables,ignore):
    mpl = Mpl(mpl_cursor)
    ignore_macros = mpl.ignore_macros()
    for tt in truth_tables:
      mpl_cursor.execute('select Z_PK from ZMACRO where ZNAME=?', (tt,))
      macro_pk = int(mpl_cursor.fetchone()[0])
      (zent, zopt) = table_zent_zopt(mpl_cursor, 'ZMACROOPTOUT')
      query = 'insert into ZMACROOPTOUT (Z_ENT, Z_OPT, ZMACRO, ZIGNOREMACRO) values (?, ?, ?, ?)'
      ignore_fk = ignore_macros[ignore]
      mpl_cursor.execute(query, (zent, zopt, macro_pk, ignore_fk))
      print indent('Ignored when {0} added to {1}'.format(ignore,tt))


def process_args(argv=None):
  if argv is None:
      argv = sys.argv[1:]
  
  parser = argparse.ArgumentParser(description='patch MPS Logic files.', formatter_class=argparse.RawDescriptionHelpFormatter)
  parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
  parser.add_argument(
    'mpl', metavar='MPL_FILE', type=argparse.FileType(),
    help='path of MPL file to be patched'
  )
  parser.add_argument(
    'patches', metavar='PATCH_FILE', type=argparse.FileType(), nargs='+',
    help='path of patch file to be applied to MPL file'
  )
  parser.add_argument(
    'condition', metavar='CONDITION', nargs=1,
    help='String of new condition to apply to list of truth tables'
  )
    
  parser.add_argument(
    '-n', '--dry-run', action='store_true', default=False,
    help='report patch actions on MPL file without actually applying them')
    
  try:
    args = parser.parse_args(argv)
  except IOError as e:
    sys.stderr.write("{0.strerror}: '{0.filename}'\n".format(e))
    sys.exit(1)

  return args

def main(argv=None):
    args = process_args(argv)

    all_truth_tables = []
    for patch_file in args.patches:
        try:
            patch = json.load(patch_file)
        except (ValueError) as e:
            print '{0} in patch file "{1}"'.format(e, patch_file.name)
            return 1
        all_truth_tables.extend(patch['truth_tables'])
        patch_file.close()
        
    try:
        connection = sqlite3.connect(args.mpl.name)
        connection.row_factory = sqlite3.Row
        mpl_cursor = connection.cursor()
        ignore=args.condition[0]

        verify_condition(mpl_cursor, ignore)
        apply_condition(mpl_cursor, all_truth_tables,ignore)

        if args.dry_run:
            connection.rollback()
        else:
            connection.commit()
    except MplError as e:
        print 'MPS Logic Patch Error:', e
        return 2
    finally:
        connection.close()
        args.mpl.close()

    return 0


if __name__ == '__main__':
    status = main(sys.argv[1:])
    sys.exit(status)