#!/usr/bin/env python
import argparse
import sys
import os
import imp

# This is the divider that's used for some subcommands.
divider = "=" * 70


def build_site(dir, **args):
    "This is what will be called when the user runs `cytoplasm build`"
    import cytoplasm
    cytoplasm.build(dir)


def init_site(site, **args):
    "This is the function called when you run `cytoplasm init something`"
    sites = {
            "bare": "git://github.com/startling/cytoplasm-bare.git",
            "cytoplasm-site": "git://github.com/startling/cytoplasm-site.git",
    }
    os.system("git clone %s ." % (sites[site]))
    os.system("git submodule init")
    os.system("git submodule update")


def serve_site(port, rebuild, **args):
    """This is the function called when you run `cytoplasm serve`:
    serve the site in the build_dir.
    """
    import cytoplasm.server
    print(divider)
    print("Serving your site on port %d..." % (port))
    print(divider)
    cytoplasm.server.serve(port, rebuild)


def test_cytoplasm(test_controllers, **args):
    "This is the function called when you run `cytoplasm test`; test"
    import unittest
    print(divider)
    print("Running Cytoplasm's unittests:")
    # load the the tests in `cytoplasm` that match `test*.py`.
    all_tests = unittest.TestLoader().discover('cytoplasm', pattern='test*.py')
    # and run them:
    unittest.TextTestRunner().run(all_tests)
    print(divider)
    # if the -c flag is specified, test all the controllers in the
    # current directory:
    if test_controllers:
        for controller in os.listdir("_controllers"):
            print(divider)
            print("Testing the controller in '_controllers/%s':" %
                    (controller))
            controller_tests = unittest.TestLoader().discover(
                    os.path.join("_controllers", controller),
                    pattern='test*.py')
            unittest.TextTestRunner().run(controller_tests)
            print(divider)


class Parser(argparse.ArgumentParser):
    "A custom parser class with more helpful error messages."
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)


# Make an argparse parser, using the class above.
parser = Parser(description='a static blog compiler.', add_help=True)
# (subparsers, aka subcommands)
subparsers = parser.add_subparsers(title="Subcommands")
# "build" subparser, i.e. build the site
build = subparsers.add_parser('build',
        help='Build the cytoplasm site in the working directory.')
# Associate the build function, above, with the subcommand `build`.
build.set_defaults(func=build_site)
build.add_argument("dir", type=str,
        help="The source directory of your site; defaults to cwd.",
        action="store", nargs="?", default=".")
# "init" subparse
init = subparsers.add_parser('init',
        help='Clone a repository to work from (requires Git).')
init.set_defaults(func=init_site)
init.add_argument('site', choices=["bare", "cytoplasm-site"],
        help="The site you want to clone.")
# serve subparser
serve = subparsers.add_parser('serve',
        help="Serve your site with Python's built-in server.")
serve.set_defaults(func=serve_site)
serve.add_argument("port", type=int,
        help="The port to serve on; defaults to 8080.", action="store",
        nargs="?", default=8080)
serve.add_argument('-r', '--rebuild',
        help="Re-build the site automatically when changes are made.",
        action="store_true")
# test subparser
test = subparsers.add_parser('test',
        help="Test Cytoplasm with the built-in tests. (Requires nose).")
test.set_defaults(func=test_cytoplasm)
test.add_argument("-c", "--test-controllers", action="store_true",
        help="Run tests for the controllers in this site directory.")
# Parse the arguments from the command line.
args = parser.parse_args()
# run the functions associated with the arguments.
args.func(**vars(args))
