# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import inspect

from django.http import HttpRequest
from django.utils import six


def inject_request(func):
	argspec = inspect.getargspec(func)
	assert 'request' in argspec.args, "There must be a 'request' argument in the function."
	index = argspec.args.index('request')
	assert index in [0, 1], "The 'request' argument must be, at most, the second positional argument."
	assert len(argspec.args) - len(argspec.defaults or []) == index, "All arguments after (and including) 'request' must have default values."
	def wrapper(*args, **kwargs):
		request = None
		frame = inspect.currentframe().f_back
		while frame and not request:
			for v_name, v_object in six.iteritems(frame.f_locals):
				if isinstance(v_object, HttpRequest):
					request = v_object
					break
			frame = frame.f_back
		if request:
			kwargs.setdefault('request', request)
		return func(*args, **kwargs)
	return wrapper