import datetime
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from sqlalchemy import engine_from_config
from .models import initialize_sql
from .security import groupfinder, RootFactory
from .renderers import json_renderer


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)

    session_factory = UnencryptedCookieSessionFactoryConfig('picard')

    authentication_policy = AuthTktAuthenticationPolicy('picard', timeout=900, reissue_time=90, callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()

    config = Configurator(
        settings=settings,
        root_factory=RootFactory,
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
        session_factory=session_factory
    )

    config.add_renderer(name='json', factory=json_renderer)

    def get_age(days):
        return datetime.timedelta(days=days).total_seconds()

    def add_route(name, url, has_list=True, variable='id'):
        def pluralize(word):
            if word.endswith('y'):
                return word[:-1] + 'ies'
            elif word[-1] in 'sx' or word[-2:] in ['sh', 'ch']:
                return word + 'es'
            elif word.endswith('an'):
                return word[:-2] + 'en'
            else:
                return word + 's'

        config.add_route(name + '_' + variable, url + '/{' + variable + '}')
        config.add_route(name, url)
        if has_list:
            config.add_route(name + '_list', pluralize(url))

        config.add_route('api_' + name + '_' + variable, '/api' + url + '/{' + variable + '}')
        config.add_route('api_' + name, '/api' + url)


    config.add_static_view('icons', 'picard:static/icons', cache_max_age=get_age(10))
    config.add_static_view('assets', 'picard:static/assets', cache_max_age=get_age(10))
    config.add_static_view('features', 'picard:static/features', cache_max_age=get_age(10))
    config.add_static_view('fonts', 'picard:static/fonts', cache_max_age=get_age(10))
    config.add_static_view('img', 'picard:static/img', cache_max_age=get_age(10))
    config.add_static_view('js', 'picard:static/js', cache_max_age=get_age(10))
    config.add_static_view('script', 'picard:static/scripts', cache_max_age=get_age(1))
    config.add_static_view('css', 'picard:static/css', cache_max_age=get_age(10))
    config.add_static_view('partials', 'picard:static/partials', cache_max_age=get_age(10))
    config.add_static_view('template', 'picard:static/template', cache_max_age=get_age(10))

    config.add_route('api_auth', '/api/Auth')
    config.add_route('api_login', '/api/Login')
    config.add_route('login', '/Login')
    config.add_route('logout', '/Logout')
    add_route('user', '/User')
    add_route('tax', '/Tax')
    add_route('product', '/Product')
    add_route('product_group', '/ProductGroup')
    add_route('food_table', '/FoodTable')
    add_route('modifier', '/Modifier')

    config.add_route('api_table_list', '/api/Tables')
    config.add_route('table_list', '/Tables')

    config.add_route('api_table_id', '/api/Table/{id}')
    config.add_route('table_id', '/Table/{id}')
    config.add_route('api_voucher_id', '/api/Voucher/{id}')
    config.add_route('voucher_id', '/Voucher/{id}')
    config.add_route('api_voucher', '/api/Voucher')
    config.add_route('voucher', '/Voucher')

    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()
