"""Define the `mydriver.main` way of controlling experiments.
"""
import sys
import logging

from .tools import flatten
from .api0 import open_db as sql_db, parse_dbstring
from .sql import HOST, HOST_WORKDIR, EXPERIMENT, FUCKED_UP
from .sql import insert_dict, hash_state

logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)


class Cmd(object):

    """ A callable object that attaches documentation strings to command functions.

    This class is a helper for the decorators `cmd` and `cmd_desc`.
    """

    def __init__(self, f, desc):
        self.f = f
        self.desc = desc

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

cmd_dct = {}


def cmd(f):
    """Declare a function `f` as a `mydriver.main` command.

    The docstring of `f` is taken as the description of the command.
    """
    cmd_dct[f.__name__] = Cmd(f, f.__doc__)
    return f
mydriver_cmd = cmd


def cmd_desc(desc):
    """Declare a function `f` as a `mydriver.main` command, and provide an explicit description to appear to the right of your command when running the 'help' command.
    """
    def deco(f):
        cmd_dct[f.__name__] = Cmd(f, desc)
        return f
    return deco
mydriver_cmd_desc = cmd_desc


def help(db, **kwargs):
    """Print help for this program"""
    print "Usage: %s <cmd>" % sys.argv[0]
    # TODO
    print "Commands available:"
    for name, cmd in cmd_dct.iteritems():
        print "%20s - %s" % (name, cmd.desc)


@cmd
def clear_db(db, **kwargs):
    """Delete all entries from the database """
    class y (object):
        pass
    really_clear_db = False
    n_records = len([i for i in db])
    try: