__author__ = 'RemiZOffAlex'
__copyright__ = '(c) RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

from . import jsonrpc
from .. import app, lib, models


@jsonrpc.method('user.pages')
def user_pages_list(id: int, page: int) -> list:
    """Список статей пользователя
    """
    user = models.db_session.query(
        models.User
    ).filter(
        models.User.id == id
    ).first()
    if user is None:
        raise ValueError
    pages = models.db_session.query(
        models.Page
    ).filter(
        models.Page.user_id == id
    ).order_by(
        models.Page.title.asc()
    )
    pages = lib.getpage(
        pages,
        page,
        app.config['ITEMS_ON_PAGE']
    ).all()

    result = []
    for page in pages:
        newRow = page.as_dict()
        newRow['user'] = page.user.as_dict()
        newRow['tags'] = []
        for tagLink in page.tags:
            newRow['tags'].append(tagLink.tag.as_dict())
        result.append(newRow)
    return result


@jsonrpc.method('user.pages.count')
def user_pages_count(id: int) -> int:
    """Общее количество статей
    """
    user = models.db_session.query(
        models.User
    ).filter(
        models.User.id == id
    ).first()
    if user is None:
        raise ValueError
    result = models.db_session.query(
        models.Page
    ).filter(
        models.Page.user_id == id
    ).count()
    return result


@jsonrpc.method('users')
def users_list(page: int) -> list:
    """Показать список пользователей
    """
    users = models.db_session.query(
        models.User
    )
    users = lib.getpage(
        users,
        page,
        app.config['ITEMS_ON_PAGE']
    ).all()

    result = []
    for item in users:
        result.append(item.as_dict())
    return result


@jsonrpc.method('users.count')
def users_count() -> int:
    """Количество список пользователей
    """
    result = models.db_session.query(
        models.User
    ).count()

    return result
