#!/usr/bin/env python3

import sys
import argparse
import os
from api.colors import print_error, print_prompt, print_option

try:
    import api.course
except ImportError as err:
    print_error("Missing Module: {module}".format(module=err))
    sys.exit(1)


def run_course(args):
    try:
        course = api.course.Course.load(args.path)
        course.describe()
        course.serve()
    except FileNotFoundError as err:
        print_error(
            "Course {file} could not be loaded. Does the file exist?".format(file=err)
        )


def List(args):
    courses = os.listdir("courses")
    if courses:
        print_prompt("The following courses were found:")
        for idx, course in enumerate(courses):
            print_option("{idx}. {course}".format(idx=idx + 1, course=course))
    else:
        print_error("No courses were found")


def parse(args):
    global parser
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest="subcommand")

    run = subparsers.add_parser("run", help="Run a course stored in a directory.")
    run.add_argument("path", help="Directory containing the course.yaml file")
    run.set_defaults(func=run_course)

    ls = subparsers.add_parser(
        "list", help="Show all the available courses in the courses directory."
    )
    ls.set_defaults(func=List)
    return parser.parse_args(args)


if __name__ == "__main__":
    try:
        args = parse(sys.argv[1:])
        args.func(args)
        sys.exit(0)
    except AttributeError as e:
        print_error(e)
        parser.print_usage()
        sys.exit(1)
