#!/usr/bin/env python3

import falcon
from falcon_multipart.middleware import MultipartMiddleware
from beaker.middleware import SessionMiddleware

from middleware import (
    AuthMiddleware,
    JSONTranslator,
    ConnectionMiddleware,
    static,
    handle_404
)
from models.db import StorageEngine
from controllers.main import (
    AppLogin, AppLogout, AppAdmin, AppEmisor, AppConfig,
    AppMain, AppValues, AppPartners, AppProducts, AppInvoices, AppFolios,
    AppDocumentos, AppFiles, AppPreInvoices
)
from settings import DEBUG


db = StorageEngine()

api = falcon.API(middleware=[
    AuthMiddleware(),
    JSONTranslator(),
    ConnectionMiddleware(),
    MultipartMiddleware(),
])
api.req_options.auto_parse_form_urlencoded = True
api.add_sink(handle_404, '')

api.add_route('/', AppLogin(db))
api.add_route('/logout', AppLogout(db))
api.add_route('/admin', AppAdmin(db))
api.add_route('/emisor', AppEmisor(db))
api.add_route('/folios', AppFolios(db))
api.add_route('/main', AppMain(db))
api.add_route('/values/{table}', AppValues(db))
api.add_route('/files/{table}', AppFiles(db))
api.add_route('/config', AppConfig(db))
api.add_route('/doc/{type_doc}/{id_doc}', AppDocumentos(db))
api.add_route('/partners', AppPartners(db))
api.add_route('/products', AppProducts(db))
api.add_route('/invoices', AppInvoices(db))
api.add_route('/preinvoices', AppPreInvoices(db))


if DEBUG:
    api.add_sink(static, '/static')


session_options = {
    'session.type': 'file',
    'session.cookie_expires': True,
    'session.data_dir': '/tmp/cache/data',
    'session.lock_dir': '/tmp/cache/lock',
}
app = SessionMiddleware(api, session_options)

