from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.renderers import JSON, JSONP
from pyramid.session import SignedCookieSessionFactory
from sqlalchemy import engine_from_config
from pyramid.renderers import render_to_response
from .models import DBSession, get_user
from .security import EntryFactory, groupfinder
import locale


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    # Extract secrets from configuration file
    CookiesPasswd = settings.get('secret_Cookies', 'itsthefirstseekreet')
    AuthTktPasswd = settings.get('secret_AuthTkt', 'itsthesecondseekreet')
    my_session_factory = SignedCookieSessionFactory(CookiesPasswd)
    authentication_policy = AuthTktAuthenticationPolicy(AuthTktPasswd,
                    callback=groupfinder, hashalg='sha512', debug=True)
    authorization_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings,
                          root_factory='.security.RootFactory',
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy
                          )
    config.add_renderer('json', JSON(indent=4))
    config.add_renderer('jsonp', JSONP(param_name='callback'))
    config.set_session_factory(my_session_factory)
    config.add_request_method(get_user, 'user', reify=True)
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('img', 'static/img', cache_max_age=3600)
    config.add_static_view('css', 'static/css', cache_max_age=3600)
    config.add_static_view('js', 'static/js', cache_max_age=3600)
    config.add_static_view('vendor', 'static/vendor', cache_max_age=3600)
    config.add_static_view('upload', 'upload', cache_max_age=3600)
    
    config.add_route('tester', '/tester')    

    # ICal Routes
    config.add_route('progr_iCal', '/{year:\d+}/JM2L.ics')
    
    # JSON Routes
    config.add_route('users_json', '/json-users')
    config.add_route('tiers_json', '/json-tiers')
    config.add_route('progr_json', '/{year:\d+}/le-prog-json')
    config.add_route('timeline_json', '/{year:\d+}/timeline-json')      
    
    # Session setting Routes
    config.add_route('year', '/year/{year:\d+}')
    
    # HTML Routes - Staff
    config.add_route('list_task',  '/Staff')
    config.add_route('handle_pole',   '/Staff/poles{sep:/*}{pole_id:(\d+)?}')
    config.add_route('handle_task',   '/Staff/tasks{sep:/*}{task_id:(\d+)?}')
    config.add_route('action_task', '/Staff/{action:(\w+)}/{task_id:(\d+)}')

    # HTML Routes - Public
    config.add_route('home', '/')
    config.add_route('presse', '/{year:\d+}/dossier-de-presse')
    config.add_route('edit_presse', '/{year:\d+}/dossier-de-presse/edit')    
    config.add_route('programme', '/{year:\d+}/le-programme')
    config.add_route('plan', 'nous-rejoindre')
    config.add_route('participer', 'participer-l-evenement')
    config.add_route('captcha', '/captcha')
    
    ## Events
    config.add_route('event', '/event/{year:\d+}/{event_id:([\w-]+)?}')
    config.add_route('link_event', '/MesJM2L/{year:\d+}/{intervention:\w+}/link')    
    config.add_route('edit_event', '/MesJM2L/{year:\d+}/{intervention:\w+}{sep:/*}{event_id:([\w-]+)?}')
    
    ## Entities  
    config.add_route('entities', '/entities') #{sep:/*}{Nature:\w+?}')
    config.add_route('add_entity',  '/entity')    
    config.add_route('show_entity', '/entity/{tiers_type:(\w+)}/{entity_id:([\w-]+)?}')
    config.add_route('edit_entity', '/entity/{tiers_type:(\w+)}/{entity_id:([\w-]+)}/edit')
    
    config.add_route('edit_entity_cat', '/categorie/entity')
    
    ## Users
    config.add_route('show_user', '/user/{user_slug:([\w-]+)?}')
    
    # HTML Routes - Logged
    #config.add_route('profil', 'MesJM2L')    
    config.add_route('jm2l', '/MesJM2L')
    config.add_route('modal', '/{year:\d+}/modal/{modtype:\w+}/{id:(\d+)}')    
    
    # Handle exchanges
    config.add_route('exchange', '/{year:\d+}/exchange/{modtype:\w+}/{id:(\d+)}/{action:\w+}')

    # Handle authentication
    config.add_route('register', '/register')
    config.add_route('auth', '/sign/{action}')
    config.add_route('bymail', '/sign/jm2l/{hash}')
    
    # Handle Multimedia and Uploads
    config.add_route('media_uploadform', '/test2')
    config.add_route('media_view', '/image/{media_table:\w+}/{uid:\d+}/{name:.+}')
    config.add_route('media_upload', '/uploader/{media_table:\w+}/{uid:\d+}/proceed{sep:/*}{name:.*}')

    # To Trash routes
    config.add_route('test', '/test')   
    config.add_route('test2', '/toast{sep:/*}{uid:(\d+)?}')

    #config.add_route('link_user_entity', '/entity/{uid:(\d+)}/{year:\d+}/user/{user_id:(\d+)}')
    #config.add_route('link_role_entity', '/entity/{uid:(\d+)}/{year:\d+}/role/{role_id:(\d+)}')        
    

    config.add_route('IntAdd', '/IntAdd/{modtype:\w+}')
    config.add_route('IntProp', '/IntProp/{modtype:\w+}')    

    config.add_route('blog', '/blog/{id:\d+}/{slug}')
    config.add_route('blog_action', '/blog/{action}',
                     factory='jm2l.security.EntryFactory')

    config.scan()
    return config.make_wsgi_app()


