# -*- coding: utf-8 -*-
import logging

from aiohttp import web
from bthlabs_jsonrpc_aiohttp import JSONRPCView

LOGGER = logging.getLogger('zagony_bot.lib.application')


class HomeHubJSONRPCView(JSONRPCView):
    PUBLIC_METHODS = (
        'services.get_states', 'services.start', 'state.get_frontend',
        'system.list_methods',
    )

    async def can_call(self, request, method, args, kwargs):
        result = method in self.PUBLIC_METHODS

        if request.app['SETTINGS'].ADMIN_HOSTS == '*':
            result = True

        if request.host in request.app['SETTINGS'].ADMIN_HOSTS:
            result = True

        if result is False:
            LOGGER.warning(
                'HomeHubJSONRPCView.can_call(): Access denied! host=%s method=%s',
                request.host,
                method,
            )

        return result


class HomeHubApplication(web.Application):
    def __init__(self, settings, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self['SETTINGS'] = settings

    def get_jsonrpc_view(self):
        return HomeHubJSONRPCView()
