# -*- coding: utf-8 -*-
"""core -- core behaviors for Owyl.

Copyright 2008 David Eyk. All rights reserved.

$Author$\n
$Rev$\n
$Date$
"""

__author__ = "$Author$"[9:-2]
__revision__ = "$Rev$"[6:-2]
__date__ = "$Date$"[7:-2]

import logging

try:
    from mx.Stack import Stack, EmptyError
except ImportError:
    from stack import Stack, EmptyError

RETURN_VALUES = set((True, False, None))

__all__ = ['wrap', 'task', 'taskmethod', 'parent_task', 'parent_taskmethod', 'visit', 
           'succeed', 'fail', 'succeedAfter', 'failAfter', 
           'sequence', 'selector', 'parallel', 'PARALLEL_SUCCESS',
           'queue', 'parallel_queue',
           'throw', 'catch',
           'log',]


def wrap(func, *args, **kwargs):
    """Wrap a callable as a task. Yield the boolean of its result.
    """
    def initTask(**initkwargs):
        def makeIterator(**runkwargs):
            result = func(*args, **kwargs)
            yield bool(result)
        try: makeIterator.__name__ = func.__name__
        except AttributeError: pass
        try: makeIterator.__doc__ = func.__doc__
        except AttributeError: pass
        return makeIterator
    try: initTask.__doc__ = func.__doc__
    except AttributeError: pass
    try: initTask.__name__ = func.__name__
    except AttributeError: pass
    return initTask


def task(func):
    """Task decorator.

    Decorate a generator function to produce a re-usable generator
    factory for the given task.
    """
    def initTask(**initkwargs):
        def makeIterator(**runkwargs):
            runkwargs.update(initkwargs)
            iterator = func(**runkwargs)
            return iterator
        try: makeIterator.__name__ = func.__name__
        except AttributeError: pass
        try: makeIterator.__doc__ = func.__doc__
        except AttributeError: pass
        return makeIterator
    try: initTask.__doc__ = func.__doc__
    except AttributeError: pass
    try: initTask.__name__ = func.__name__