#!/usr/bin/env python
"""
 CIJOE test reporter
"""
from __future__ import print_function
import argparse
import sys
import os
import cij.reporter
import cij.runner
import cij.util
import cij

def parse_args(cij_conf):
    """Parse command-line arguments for cij_reporter"""

    # Parse the Command-Line
    prsr = argparse.ArgumentParser(
        description='cij_reporter - CIJOE Test Runner',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    prsr.add_argument(
        'output',
        help="Path to test output",
        default=os.getcwd()
    )
    prsr.add_argument(
        '--template',
        help="Path to report template",
        default=os.sep.join([cij_conf["TEMPLATES"], "report.html"])
    )
    prsr.add_argument(
        '--force',
        help="Overwrite possibly existing report",
        action='store_true'
    )
    args = prsr.parse_args()

    args.output = cij.util.expand_path(args.output)
    if not os.path.exists(args.output):
        cij.err("output: %r, does not exist" % args.output)
        return None

    args.trun_fpath = cij.runner.yml_fpath(args.output)
    if not os.path.exists(args.trun_fpath):
        cij.err("trun_fpath: %r" % args.trun_fpath)
        return None

    args.template = cij.util.expand_path(args.template)
    if not os.path.exists(args.template):
        cij.err("template: %r, does not exist" % args.template)
        return None

    # Expand and construct template paths
    args.tmpl_fpath = args.template
    args.tmpl_fname = os.path.basename(args.tmpl_fpath)
    args.tmpl_name = os.path.splitext(args.tmpl_fname)[0]

    return args

def main():
    """
    Parse environment variables and command-line arguments constructing a
    configuration for which to invoke the reporter
    """

    cij_conf = cij.paths_from_env("CIJ", [
        "ROOT", "ENVS", "TESTPLANS", "TESTCASES", "TESTSUITES", "MODULES",
        "HOOKS", "TEMPLATES"
    ])
    if None in [val for _, val in cij_conf.iteritems()]:
        cij.err("rprtr: failed parsing CIJOE config from environment variables")
        return 1

    args = parse_args(cij_conf)
    if args is None:
        cij.err("rprtr: failed parsing command-line args")
        return 1

    rcode = cij.reporter.main(args, cij_conf)
    if rcode:
        cij.err("rprtr: rcode: %r, error while creating report" % rcode)

    return rcode

if __name__ == "__main__":
    sys.exit(main())
