# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns,url
from types import FunctionType
from django.core.urlresolvers import RegexURLPattern


def urlmapper(view_path,*args,**kwargs):
    '''
    This method creates urlpatterns based on view functions that have 'request' as their first parameter.

    Usage:
        urlpatterns = urlmapper('path.to.views'[, custom_url_patterns][, url_prefix][, url_name_prefix][, slug_names][, int_names])

    3 types of url scheme can be created automaticaly:
        plain:
            http://.../list_articles/ >>> def list_articles(request):
        integer
            http://.../show_article/3565/ >>> def show_article(request, id):
        slug
            http://.../show_articel/title_of_article/ >>> def show_article(request, slug):

    ** Variable names should be listed in the related lists: (default values can be seen bellow)
            urlpatterns = urlmapper('path.to.views',slug_names=['my_slug_name']) >>> def show_article(request, my_slug_name)

    ** Custom url patterns can be appended just like normal patterns method:        
            urlpatterns += urlmapper('path.to.views',
                    url(r'^custom_url/(?P<custom_var_name>\d+)/$', view, name='custom_url_name'),
                    (r'^another_url/$', 'another_view'),
                    )
        note: These custom mapped views will be excluded from automapping.
        
    ** Urls can be prefixed with 'url_prefix' keyword parameter:
            urlpatterns = urlmapper('support.views',url_prefix='members/')

    ** Url pattern names can be prefixed with 'url_name_prefix' keyword parameter:
            urlpatterns = urlmapper('support.views',url_name_prefix='sup_')

    ** Keyword arguments should follow any possible custom urlpatterns:
            urlpatterns = urlmapper('path.to.views',
                    (r'^another_url/$', 'another_view'),url(r'^surl/$', vi,name='viii'),
                    url_prefix='members/',url_name_prefix='sup_')
        

    '''
    slug_names=kwargs.get('slug_names',['slug','key','name'])
    int_names=kwargs.get('int_names',['id','pk','no'])
    pfx=kwargs.get('url_name_prefix','')
    url_prefix=kwargs.get('url_prefix','')
    custom_urls=[type(u)==RegexURLPattern and u.callback or u[1] for u in args]
    ul=[]
    exec  'import %s as mdl' % view_path
    for name, obj in mdl.__dict__.iteritems():
        if hasattr(obj, 'view_func'):
            obj=obj.view_func
        elif hasattr(obj, '__closure__') and obj.__closure__:
            obj=obj.__closure__[0].cell_contents
        if type(obj)!=FunctionType or name in custom_urls: continue        
        fc=getattr(obj,'func_code')
        if fc.co_varnames[0]=='request':
            url_name='%s%s'%(pfx,name)
            if fc.co_argcount==1:
                ul.append(url(r'^%s%s/$'%(url_prefix,name),name,name=url_name))
            elif fc.co_argcount==2:
                if fc.co_varnames[1] in int_names:
                    ul.append(url(r'^%s%s/(?P<%s>\d+)/$'%(url_prefix,name,fc.co_varnames[1]), name,name=url_name) )
                elif fc.co_varnames[1] in slug_names:
                    ul.append(url(r'^%s%s/(?P<%s>[\w-]+)/?$'%(url_prefix,name,fc.co_varnames[1]), name,name=url_name) )
    up=[]
    for p in ul+list(args): up.extend(patterns(view_path,p))
    return up