'''
A decorator to collect preflight checks.
'''
from functools import wraps
import logging
logger = logging.getLogger(__name__)


preflights = []
preflight_conditions = {}


def preflight(_func=None, *args, require_config=True, **kwargs):

    def inner(func):

        @wraps(func)
        def wrapper(runner, *args, **kwargs):
            """A wrapper function"""
            from oaa.settings import config

            # Extend some capabilities of func
            logger.debug('running %s preflight', func.__name__)

            if 'config' not in preflight_conditions:
                preflight_conditions['config'] = config

            # TODO simplify this. I want preflights to be simpler
            # i.e. they could just return true/false
            # i.e. they could just assert tests like pytest
            # i.e. they could return T/F and a list of messages

            if require_config:
                if not config:
                    return ['invalid configuration - preflight check'
                            f'[{func.__name__}] cannot run']

                return func(runner, *args, config=config,
                            preflight_conditions=preflight_conditions,
                            **kwargs)

            return func(runner, *args,
                        preflight_conditions=preflight_conditions,
                        **kwargs)

        preflights.append(wrapper)

        return wrapper

    if _func is None:
        return inner

    return inner(_func)


def run_preflights(runner):

    problems = []

    for pf in preflights:
        problems.extend(pf(runner))

    return problems
