#!/usr/bin/env python
'''
Change name for existing mitigationdevice
'''

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 from ZMACRO')
        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

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

    query = 'select ZISACTIVE from ZMACRO where ZNAME = ?'
    mpl_cursor.execute(query, (device,))
    count = int(mpl_cursor.fetchone()[0])
    if verbose:
        print(('Check if exists in ZMACRO:', device))
    if count == 1:
       if verbose:
           print(('Found ', device))
    elif count == 0:
        print(('Did not find "%s". Exiting ' % device))

    else:
       raise MplError("Illegal number of instances "+count+" of "+device+". Exiting")
   
    # Otherwise, proceed
    query = 'update ZMACRO set ZISACTIVE = (?) where ZNAME = (?)'
    mpl_cursor.execute(query, (state, device))

    print('Change complete')


def process_args(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    
    parser = argparse.ArgumentParser(description='set active state.', 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(
        'device',
        help='Logic Device Name')

    parser.add_argument(
        'state',
        help='Active State: 0/1')

    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()

        print(('Set device "%s" active state to "%s"' % (args.device, args.state)))

        update_active_state(mpl_cursor, args.device, args.state, args.verbose)
        
        if args.dry_run:
            connection.rollback()
            print('** Dry Run.  Active State Not Changed **')
        else:
            connection.commit()

    except MplError as e:
        print(('MPS Mitigation Device Rename 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)


