# -*- coding: utf-8 -*-
import codecs
import datetime
import importlib
import logging
import os
import sys

from aiohttp import web
from aiojobs.aiohttp import setup as setup_aiojobs

from homehub_backend import handlers
from homehub_backend.defs import FRONTEND_DIR
from homehub_backend.lib.application import HomeHubApplication
from homehub_backend.lib.state_store import setup as setup_state_store
from homehub_backend.lib.services import setup as setup_services
from homehub_backend.lib.websocket import setup as setup_websocket

settings = importlib.import_module(
    os.environ.get('HOMEHUB_SETTINGS_MODULE', 'settings'),
)

logger = logging.getLogger('homehub')
if getattr(settings, 'TESTING', False):
    logger.setLevel(logging.WARNING)
elif settings.DEBUG:
    logger.setLevel(logging.DEBUG)
else:
    logger.setLevel(logging.INFO)

handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
    '%(asctime)s %(name)s: %(levelname)s: %(message)s',
)
handler.setFormatter(formatter)
logger.addHandler(handler)

app_logger = logging.getLogger('homehub.app')


async def app_on_startup(app):
    logger.info('HomeHub 1.0 by BTHLabs')
    if app['SETTINGS'].DEBUG:
        logger.debug('Running with DEBUG=True')

    app['STARTUP_TS'] = datetime.datetime.now()

    logger.debug('My PID = {pid}'.format(pid=os.getpid()))


def create_app(loop=None):
    application_class = getattr(
        settings, 'APPLICATION_CLASS', HomeHubApplication,
    )
    app = application_class(settings, logger=app_logger, loop=loop)

    app.on_startup.append(app_on_startup)

    setup_aiojobs(app)
    setup_state_store(app)
    setup_services(app)
    setup_websocket(app)

    frontend_dir = getattr(settings, 'FRONTEND_DIR', FRONTEND_DIR)
    index_html_path = os.path.join(frontend_dir, 'index.html')
    if os.path.isfile(index_html_path):
        with codecs.open(index_html_path, 'r', 'utf-8') as index_html_f:
            app['INDEX_HTML'] = index_html_f.read()

    app.add_routes([
        web.post('/backend/rpc', app.get_jsonrpc_view()),
        web.get('/', handlers.get_index),
        web.get('/index.html', handlers.get_index),
    ])

    if os.path.isdir(frontend_dir):
        static_path = getattr(settings, 'STATIC_PATH', 'frontend')
        app.add_routes([
            web.static(f'/{static_path}', frontend_dir),
        ])

    return app


app = create_app()
