#! /usr/bin/env python3
""" Script to generate header file from YAML file """

import argparse
import sys
import os

try:
    import yaml
except ImportError as e:
    print("Failed to import yaml: " + str(e))
    print("")
    print("You may need to install it using:")
    print("    pip3 install --user pyyaml")
    print("")
    sys.exit(1)


parser = argparse.ArgumentParser(description='Generate function header from yaml')

parser.add_argument('yaml_file', type=str, help='YAML config file')
parser.add_argument('output_file', type=str, help='.hpp header file')

args = parser.parse_args()
yaml_file = args.yaml_file
output_file = args.output_file

def load_yaml_file(file_name):
    with open(file_name, 'r') as stream:
        try:
            return yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)
            raise

document = load_yaml_file(yaml_file)
functions = document['functions']
all_indexes=set()
function_defs = ''

def add_function(index, name, check_duplicate=True):
    global all_indexes, function_defs
    if check_duplicate and index in all_indexes:
        raise Exception('Duplicate function with index {0} ({1})'.format(index, name))
    all_indexes.add(index)

    function_defs += '\t{0} = {1},\n'.format(name, index)

for group_key in functions:
    group = functions[group_key]
    for function_name in group:
        if isinstance(group[function_name], int):
            add_function(group[function_name], function_name)
        elif not 'count' in group[function_name]:
            add_function(group[function_name]['start'], function_name)
        else:
            start = group[function_name]['start']
            count = group[function_name]['count']
            for i in range(count):
                add_function(start+i, function_name+str(i+1))
            add_function(start+count-1, function_name+'Max', False)
            function_defs += '\n'


with open(output_file, 'w') as outfile:
    outfile.write('''
#pragma once

// This file is auto-generated by {0} from {1}

#include <stdint.h>

enum class OutputFunction : int32_t {{
{2}
}};
'''.format(os.path.basename(__file__), yaml_file, function_defs))
