import logging
from contextlib import contextmanager
from path import Path
from pynpact import parsing, executors

logger = logging.getLogger('pynpact')

from pynpact.steps import extract, extract_json, allplots, acgt_gamma, nprofile


def resolve_verb(verb):
    "Convert the verb into something that has the plan function"
    mod = {'extract': extract,
           'extract_json': extract_json,
           'nprofile': nprofile,
           'allplots': allplots,
           'acgt_gamma': acgt_gamma}[verb]
    return mod.plan


def process(verb, config, executor=None, outputdir=None):
    assert executor
    planner = resolve_verb(verb)
    planner(config, executor)
    return config


@contextmanager
def getexecutor(name):
    sm = None
    name = name.lower()
    try:
        if name == 'inline':
            e = executors.InlineExecutor()
        elif name == 'gevent':
            e = executors.GeventExecutor()
        else:
            raise ValueError("Unknown executor: %r" % name)
        yield e
    finally:
        if sm:
            sm.shutdown()


def run_cmdline(gbkfile, executorName):
    config = parsing.initial(gbkfile)
    with getexecutor(executorName) as executor:
        config = process('allplots', config, executor=executor)
        jid = config.get('allplots_result')
        if not Path(jid).exists():
            logging.info("Work scheduled, waiting")
            output = executor.result(jid, timeout=None)
            logging.info("Finished processing %r", gbkfile)
        else:
            output = jid
        logging.info("See output at %r", output)
