#!/usr/bin/python3
"""
@file ifatt2group.py
@copyright ESO - European Southern Observatory
@defgroup meltcs	
@brief IFTEST - Subsystem Interface Testing
Tool to extract attributes from a yaml file and write them 
"""

import os
import argparse
import yaml
from yaml.loader import SafeLoader

from datetime import datetime

def main():

    example_text = '''example:
    ifatt2group --match main --exclude feedback iftest_m2.yaml new_group_file.yaml --groupname group_main_feedback
    '''

    # Instantiate the parser
    parser = argparse.ArgumentParser(description='Tool to extract attribute names from a subsystem\'s configuration file and write them as a group in a new yaml file.',
                                     epilog=example_text,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    
    # Required URL, PATH and FILENAME
    parser.add_argument('file_in',     type=str, help='YAML configuration file with attributes section. Example: iftest_m2.yaml')
    parser.add_argument('file_out',    type=str, help='YAML configuration file ')
    parser.add_argument('--match',     type=str, help='Matching strings separated by comma (in quotes). Example:"node1,node2"')
    parser.add_argument('--exclude',   type=str, help='Matching strings to be excluded, separated by comma (in quotes). Example:"node3,node4"')
    groupname_arg = parser.add_argument('--groupname', type=str, help='Name of the new group to be created. Must begin with "group_". Example:"group_all_attributes"')

    # Parse input arguments
    args = parser.parse_args()

    # Server,browse node and filename from input data
    file_in   = args.file_in
    file_out  = args.file_out
    match     = args.match
    exclude   = args.exclude
    groupname = args.groupname

    match_list   = []
    exclude_list = []

    # List of attributes for the group
    group_list  = []

    if match != None:
        match_list = match.split(',')

    if exclude != None:
        exclude_list = exclude.split(',')

    # If no groupnname is given, we take the first part
    # of the file name as group name    
    if groupname is None:
        groupname = 'group_' + file_out.split('.')[0]
    else:
        if groupname.startswith('group') == False:
            raise argparse.ArgumentError(groupname_arg,'Must begin with \'group_\'')

    # Read yaml file
    with open(file_in) as fd_in:
        data = yaml.load(fd_in, Loader=SafeLoader)

    attributes_dict = data['attributes']
    attributes_iter = iter(attributes_dict)

    for key in attributes_iter:
        if len(exclude_list) > 0:
            skip_this_key = False

            # Remove lines matching the exclude string
            for string in exclude_list:
                if string in key:
                    skip_this_key = True

            if skip_this_key:
                continue

        if len(match_list) > 0:
            skip_this_line = True

            # Remove lines not matching the match string
            for string in match_list:
                if string in key:
                    skip_this_line = False

            if skip_this_line:
                continue
        
        # Populate group list
        group_list.append(key)

    # Create group using the given group name
    # and the list of appended keys
    group_dict = { groupname : group_list}

    print('==> Writing YAML file: {}'.format(file_out))

    with open(file_out,'w') as outfile:
        outfile.write('# YAML file generated with tool ifatt2group\n')
        outfile.write('# Date: {}\n\n'.format(datetime.now().strftime('%Y%m%dT%H:%M:%S')))
        yaml.dump({'groups': group_dict}, outfile, sort_keys=False)

    # Remove the dashes from each attribute line
    with open(file_out) as old, open('tmpfile', 'w') as new:
        for line in old:
            if '- ' in line:
                line = line.replace('- ','  ')
            new.write(line)
    os.rename('tmpfile',file_out)

if __name__ == "__main__":
    main()