import time
import logging
from functools import wraps
from functools import update_wrapper

from .context import g


app_logger = logging.getLogger('app')


def safe_network(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        while True:
            try:
                return func(*args, **kwargs)
            except Exception as exc:
                app_logger.error(exc)
                time.sleep(1)

    return wrapper


def copy_threading_context(func):
    main_thridng_g_ctx = g.get_context()

    def wrapper(*args, **kwargs):
        g.update_context(main_thridng_g_ctx)
        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)
