from apistar import Route
from apistar.http import HTMLResponse
from apistar_jwt import JWT
import logbook
from sqlalchemy import create_engine
from pathlib import Path

from cookie_api.auth import auth_routes
from cookie_api.logger import global_init
from cookie_api.resources import cookie_routes
from cookie_api.util import SQLAlchemyHook, SQLAlchemySession, MetaApp as App

BASEDIR = Path(__file__).parent
TEMPLATE_DIR = BASEDIR.joinpath('templates')
STATIC_DIR = BASEDIR.joinpath('static')

logger = logbook.Logger(__name__)

engine = create_engine('postgresql://apistar@localhost:5432/apistar')

app_settings = {
    "LOGGING": {
        "LEVEL": "DEBUG"
    }
}


def return_index_html():
    with open(STATIC_DIR.joinpath('index.html'), mode='rb') as f:
        return HTMLResponse(content=f.read())


index = Route('/', 'GET', return_index_html)

_routes = cookie_routes + auth_routes + [index]

_hooks = [SQLAlchemyHook]

_components = [
    SQLAlchemySession(engine=engine),
    JWT({
        'JWT_USER_ID': 'sub',
        'JWT_SECRET': 'thisisasecret',
    }),
]


def application_factory(routes=_routes, components=_components, hooks=_hooks, settings={}, template_dir=TEMPLATE_DIR,
                        static_dir=STATIC_DIR):
    """Returns an instance of Cookie API"""
    _settings = {**app_settings, **settings}

    global_init(_settings)
    logger.info("Template directory {}".format(TEMPLATE_DIR))
    logger.info("Static directory {}".format(STATIC_DIR))

    return App(components=components,
               event_hooks=hooks,
               routes=routes,
               template_dir=template_dir.name,  # have to use name because of Jinja2
               static_dir=static_dir)