#!/usr/bin/env python3
#
# Make a web page from a YAML test case file.
#

import sys
import yaml
from jinja2 import Environment, FileSystemLoader

TEMPLATE_DIR="."

# This command makes sure the following formatting applies for the respective
# sections:
#
# pre-conditions:
#  - Start line with '#' or '$' for commands, everything else is a comment.
#
# expected:
#  - Start line with '>' for command output, everything else is a comment.
#
# run: steps:
#  - Star '#' for comments , everything else is a command.
#
def comments_commands(lines, run=False):
    processed_lines = []
    for line in lines:        
        p, c = '', ''
        sline = line.strip()

        if not sline:
            processed_lines.append((p, c))
            continue

        if run:
            if sline[0] == '#':
                # Remove the '#' with the slice [1:]
                processed_lines.append((sline[1:], ''))
            else:
                # Add the '$ ' in the line for the command
                processed_lines.append(('', '$ '+sline))
        else:
            if sline[0] == '$':
                processed_lines.append(('', sline))
            elif sline[0] == '>':
                processed_lines.append(('', sline[1:].split('\n')))
            else:
                processed_lines.append((sline, ''))

    return processed_lines

def parse_format(testcase_data):
    template_values = {}

    # Mandatory fields
    metadata = testcase_data.get('metadata')
    if not metadata:
        print("Error: missing mandatory field metadata")
        sys.exit(1)

    for mv in ['name', 'image-type', 'image-arch', 'type',
               'exec-type', 'priority', 'description', 'expected']:
        value = metadata.get(mv)
        if value:
            if mv == 'expected':
                template_values.update({ mv : comments_commands(value) })
            else:
                template_values.update({ mv.replace('-', '_') : value })
        else:
            print("Error: missing mandatory field", mv)
            sys.exit(1)

    run = testcase_data.get('run')
    if not run:
        print("Error: missing mandatory field run")
        sys.exit(1)
    else:
        steps = run.get('steps')
        if not steps:
            print("Error: missing mandatory field steps for run")
            sys.exit(1)
        template_values.update({ 'run_steps' :
                                 comments_commands(steps, run=True) })

    # No mandatory fields
    for nm in ['notes', 'format', 'maintainer', 'resources', 'pre-conditions']:
        value = metadata.get(nm)
        if value:
            template_values.update({ nm.replace('-', '_') :
                                     comments_commands(value)
                                     if nm in ['notes', 'pre-conditions']
                                     else value })

    install = testcase_data.get('install')
    if install:
        deps = install.get('deps')
        if not deps:
            print("Error: missing mandatory field deps for install")
            sys.exit(1)
        template_values.update({ 'install_steps' : deps })

    return template_values


if '__main__' == __name__:

    testcase_file = sys.argv[1]

    try:
        with open(testcase_file) as testcase:
            testcase_data = yaml.safe_load(testcase)
    except yaml.scanner.ScannerError as e:
        print("yaml format error:", e)
        sys.exit(1)

    env = Environment(loader=FileSystemLoader([TEMPLATE_DIR]))
    # Get template from environment and render it.
    data = env.get_template('index.html').render(parse_format(testcase_data))

    print(data)