import datetime
from pyramid.config import Configurator
from sqlalchemy import engine_from_config

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from brewman.factories import add_route
from brewman.models import initialize_sql
from brewman.renderers import json_renderer, CSVRenderer
from brewman.security import groupfinder

current_table = 1


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

    session_factory = UnencryptedCookieSessionFactoryConfig('secret')

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

    config = Configurator(
        settings=settings,
        root_factory='brewman.factories.RootFactory',
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
        session_factory=session_factory
    )
    # This changes in pyramid 1.4 to something similar to "config.add_renderer('myjson', JSON(indent=4))"
    # http://docs.pylonsproject.org/projects/pyramid/en/master/api/renderers.html#pyramid.renderers.JSON
    config.add_renderer(name='json', factory=json_renderer)
    config.add_renderer(name='csv', factory=CSVRenderer)

    def get_age(days):
        return datetime.timedelta(days=days).total_seconds()
    config.add_static_view('icons', 'brewman:static/icons', cache_max_age=get_age(10))
    config.add_static_view('assets', 'brewman:static/assets', cache_max_age=get_age(10))
    config.add_static_view('features', 'brewman:static/features', cache_max_age=get_age(10))
    config.add_static_view('fonts', 'brewman:static/fonts', cache_max_age=get_age(10))
    config.add_static_view('img', 'brewman:static/img', cache_max_age=get_age(10))
    config.add_static_view('js', 'brewman:static/js', cache_max_age=get_age(10))
    config.add_static_view('script', 'brewman:static/scripts', cache_max_age=get_age(1))
    config.add_static_view('css', 'brewman:static/css', cache_max_age=get_age(10))
    config.add_static_view('partial', 'brewman:static/partial', cache_max_age=get_age(10))
    config.add_static_view('template', 'brewman:static/template', cache_max_age=get_age(10))

    config.add_route('api_dashboard', '/api/Dashboard')
    config.add_route('dashboard', '/Dashboard')

    config.add_route('api_login', '/api/login')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')

    config.add_route('home', '/')

    config.add_route('api_account_type_list', '/api/AccountTypes')

    add_route(config, 'cost_center', '/CostCenter')
    add_route(config, 'account', '/Account')
    add_route(config, 'employee', '/Employee')
    add_route(config, 'user', '/User')
    add_route(config, 'group', '/Group')
    add_route(config, 'client', '/Client')
    add_route(config, 'product', '/Product')
    add_route(config, 'product_group', '/ProductGroup')

    config.add_route('journal_id', '/Journal/{id}')
    config.add_route('journal', '/Journal')
    config.add_route('purchase_id', '/Purchase/{id}')
    config.add_route('purchase', '/Purchase')
    config.add_route('purchase_return_id', '/Return/{id}')
    config.add_route('purchase_return', '/Return')
    config.add_route('payment_id', '/Payment/{id}')
    config.add_route('payment', '/Payment')
    config.add_route('receipt_id', '/Receipt/{id}')
    config.add_route('receipt', '/Receipt')
    config.add_route('issue_id', '/Issue/{id}')
    config.add_route('issue', '/Issue')
    config.add_route('api_issues_grid', '/api/Issues/Services/{date}')
    config.add_route('salary_deduction_id', '/SalaryDeduction/{id}')
    config.add_route('salary_deduction', '/SalaryDeduction')

    config.add_route('api_voucher_id', '/api/Voucher/{id}')
    config.add_route('api_voucher', '/api/Voucher')

    config.add_route('message_id', '/Message/{id}')
    config.add_route('message', '/Message')
    config.add_route('api_message_id', '/api/Message/{id}')
    config.add_route('api_message', '/api/Message')
    config.add_route('api_tag_list', '/api/Tags')

    config.add_route('settings', '/Settings')
    config.add_route('api_lock_info', '/api/LockInfo')

    add_route(config, 'attendance', '/Attendance', has_list=False, variable='date')
    config.add_route('api_attendance_types', '/api/AttendanceTypes')

    add_route(config, 'employee_attendance', '/EmployeeAttendance', has_list=False)

    config.add_route('attendance_report', '/AttendanceReport')
    config.add_route('api_credit_salary', '/api/CreditSalary')
    config.add_route('employee_functions', '/EmployeeFunctions')
    config.add_route('api_fingerprint', '/api/Fingerprint')

    add_route(config, 'ledger', '/Ledger', has_list=False)
    add_route(config, 'reconcile', '/Reconcile', has_list=False)
    add_route(config, 'product_ledger', '/ProductLedger', has_list=False)

    add_route(config, 'trial_balance', '/TrialBalance', has_list=False, variable='date')
    config.add_route('api_net_transactions', '/api/NetTransactions')
    config.add_route('net_transactions', '/NetTransactions')
    config.add_route('api_purchases', '/api/Purchases')
    config.add_route('purchases', '/Purchases')
    add_route(config, 'closing_stock', '/ClosingStock', has_list=False, variable='date')

    add_route(config, 'cash_flow', '/CashFlow', has_list=False)
    add_route(config, 'raw_material_cost', '/RawMaterialCost', has_list=False)

    config.add_route('api_daybook', '/api/Daybook')
    config.add_route('daybook', '/Daybook')

    config.add_route('api_unposted', '/api/Unposted')
    config.add_route('unposted', '/Unposted')

    config.add_route('api_profit_loss', '/api/ProfitLoss')
    config.add_route('profit_loss', '/ProfitLoss')

    config.add_route('api_stock_movement', '/api/StockMovement')
    config.add_route('stock_movement', '/StockMovement')

    add_route(config, 'balance_sheet', '/BalanceSheet', has_list=False, variable='date')

    config.add_route('api_purchase_entries', '/api/PurchaseEntries')
    config.add_route('purchase_entries', '/PurchaseEntries')

    config.add_route('api_auth', '/api/Auth')
    config.add_route('api_rebase', '/api/Rebase/{date}')
    config.add_route('api_reset_stock', '/api/ResetStock/{id}')

    config.add_route('api_batch', '/api/Batch')

    config.add_route('favicon', '/favicon.ico')
    config.scan()

    return config.make_wsgi_app()

