#!/usr/bin/env python
'''
Add new mitigation device to logic database.
Add to each logic truth table state
'''

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 states(self):
        '''
        Return a dictionary of truth table states
        {'state_pk': state_name, ... }
        '''
        self.cursor.execute('select Z_PK, ZNAME from ZMACROSTATE')
        return dict(self.cursor.fetchall())
    
    def mitigation_devices(self):
        '''
        Return a dictionary of mitigation device pks
        '''
        self.cursor.execute('select ZNAME, Z_PK, ZENUM from ZMITIGATIONDEVICE')
        return dict(self.cursor.fetchall())        
    

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

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

# Add mitigation device to mitigation device table
def add_mitigation_device(mpl_cursor, mitigation_device, verbose):
    mpl = Mpl(mpl_cursor)

    name = mitigation_device

    # Check if mitigation device already exists
    query = 'select count(*) from ZMITIGATIONDEVICE where ZNAME = ?'
    mpl_cursor.execute(query, (name,))
    count = int(mpl_cursor.fetchone()[0])
    if verbose:
        print(('Check if already exists in ZMITIGATIONDEVICE:', name))
    # If it does, throw exception
    if count > 0:
       if verbose:
           print(('Found, so not adding mitigation device ', name))
       raise MplError("Mitigation device "+name+" already exists. Not adding")

    # Otherwise, proceed
    if verbose:
        print(('Not found, so adding mitigaiton device "%s"' % name))

    mpl_cursor.execute('select ZENUM from ZMITIGATIONDEVICE order by ZENUM desc limit 1')
    mitigation_device_enum = 1 + int(mpl_cursor.fetchone()[0])    

    (zent, zopt) = table_zent_zopt(mpl_cursor, 'ZMITIGATIONDEVICE')
    print(('Adding {0} mitigation device'.format(name)))
    query = 'insert into ZMITIGATIONDEVICE (Z_ENT, Z_OPT, ZENUM, ZNAME) values (?, ?, ?, ?)'
    mpl_cursor.execute(query, (zent, zopt, mitigation_device_enum, name))
    mitigation_device_pk = mpl_cursor.lastrowid

    if mitigation_device_pk != mitigation_device_enum+1:
        raise MplError('Expected mitigation device ZENUM ({0}) to be 1 less than Z_PK ({1})'.format(mitigation_device_enum, mitigation_device_pk))
    
    print((indent('Added mitigation device "{0}" mitigation device (primary key {1}, enum {2})'.format(name, mitigation_device_pk, mitigation_device_enum))))
    return mitigation_device_pk

# Add new mitigation device rate for each state
def add_mitigation_device_to_states(mpl_cursor, mitigation_device_pk, verbose):
    mpl = Mpl(mpl_cursor)
    states = mpl.states()

    # Set Z_ENT and Z_OPT to match majority of existing entries
    zent = 10
    zopt = 1
    rate = 1 # Rate primary key 1 = Ignore
    print(('Adding new mitigation device to states with rate = {0}'.format(rate)))

    for k, v in states.items():
        query = 'insert into ZMACROSTATERATEATDEVICE (Z_ENT, Z_OPT, ZSTATE, ZDEVICE, ZRATE) values (?, ?, ?, ?, ?)'
        mpl_cursor.execute(query, (zent, zopt, k, mitigation_device_pk, rate))
    print((indent('Last state key {0}: new mitigation device key {1}'.format(k, mitigation_device_pk))))

def process_args(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    
    parser = argparse.ArgumentParser(description='new mitigation device.', formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-v', '--verbose', action='store_true', default=False)

    parser.add_argument(
        'mpl', metavar='MPL_FILE', type=argparse.FileType(),
        help='path of MPL file to be patched'
    )
   
    parser.add_argument(
        '-n', '--dry-run', action='store_true', default=False,
        help='report patch actions on MPL file without actually applying them')

    parser.add_argument(
        'mitigation_device',
        help='New mitigation device name')

    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 = []
    try:
        connection = sqlite3.connect(args.mpl.name)
        connection.row_factory = sqlite3.Row
        mpl_cursor = connection.cursor()

        mitigation_device_pk = add_mitigation_device(mpl_cursor, args.mitigation_device, args.verbose)
        
        add_mitigation_device_to_states(mpl_cursor, mitigation_device_pk, args.verbose)

        if args.dry_run:
            connection.rollback()
            print('** Dry Run.  Mitigation device not added. **')
        else:
            connection.commit()

    except MplError as e:
        print(('MPS Mitigation Device Add Error:', e))
        print('Attempt rollback')
        connection.rollback()
        return 2
    finally:
        connection.close()
        args.mpl.close()

    return 0


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


