import inspect

# changes a view such that it captures specified variables from the URL and sends it to the context
def view_url_vars_to_context(view):
    def view_with_uv2c(request, url_vars_to_context = {}, extra_context = {}, *args, **kwargs):

        basicargs = inspect.getargspec(view).args

        # This is going to prevent some sort of confusion at some point.
        if set(url_vars_to_context.keys()) & set(basicargs):
            raise ValueError("Context variable names from URL can't be arguments expected by generic view.")

        for varname in url_vars_to_context.keys():
            if varname not in kwargs.keys():
                raise ValueError("URL variable %s does not exist" % varname)

        for k in kwargs.keys():
            if k in url_vars_to_context:
                context_var_name = url_vars_to_context[k]
                extra_context[context_var_name] = kwargs[k]
                del kwargs[k]
        
        return view(request, extra_context=extra_context, *args, **kwargs)
    return view_with_uv2c