__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

from functools import wraps
from jsonrpc import JSONRPC
from jsonrpc.backend.flask import APIView
from flask import session

from .. import app, models


def login_required(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if 'logged_in' in session and 'user_id' in session:
            user = models.db_session.query(
                models.User
            ).filter(
                models.User.id == session['user_id']
            ).first()
            if user:
                return func(*args, **kwargs)
            else:
                session.pop('logged_in', None)
                session.pop('user_id', None)
                raise Exception('Необходима авторизация')
        else:
            raise Exception('Необходима авторизация')
    return decorated_function


jsonrpc = JSONRPC()

from . import ( # noqa F401
    login,
    favorite,
    note,
    profile,
    page,
    tag,
    user
)

app.add_url_rule('/api', view_func=APIView.as_view('api', jsonrpc=jsonrpc))


@jsonrpc.method('api.methods')
def api_methods() -> dict:
    """Список методов API
    """

    result = {}
    for method in jsonrpc.methods:
        result[method] = jsonrpc.description(method)
    return result
