#!/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, 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 update_mitigation_device_name(mpl_cursor, old_name, new_name, verbose):
    mpl = Mpl(mpl_cursor)

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

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

    print('Rename complete')


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(
        'old_name',
        help='Old mitigation device name')

    parser.add_argument(
        'new_name',
        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()

        print(('Renaming mitigation device "%s" to "%s"' % (args.old_name, args.new_name)))

        update_mitigation_device_name(mpl_cursor, args.old_name, args.new_name, args.verbose)
        
        if args.dry_run:
            connection.rollback()
            print('** Dry Run.  Mitigation device not renamed. **')
        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)


