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

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


@jsonrpc.method('user.add')
def user_add(username: str, password: str) -> dict:
    """Новый пользователь
    """
    if username is None or len(username) < 4 or len(username) > 25:
        raise ValueError('Длина логина должна быть от 4 до 25 символов')
    if password is None or len(password) < 4 or len(password) > 25:
        raise ValueError('Длина пароля должна быть от 4 до 25 символов')
    user = models.db_session.query(
        models.User
    ).filter(
        models.User.name == username
    ).first()
    if user:
        raise ValueError('Пользователь с таким логином уже существует')

    newuser = models.User(
        username
    )
    newuser.password = lib.get_hash_password(
        password,
        app.config['SECRET_KEY']
    )
    models.db_session.add(newuser)
    models.db_session.commit()

    result = newuser.as_dict()
    return result


@jsonrpc.method('user.enable')
def user_enable(id: int) -> dict:
    """Разблокировать пользователя
    """
    userRow = models.db_session.query(
        models.User
    ).filter(
        models.User.id == id
    ).first()
    if userRow is None:
        raise ValueError
    userRow.disable = False
    models.db_session.commit()
    return userRow.as_dict()


@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 = 1,
    order_by: dict = {'field': 'name', 'order': 'asc'}
) -> list:
    """Показать список пользователей
    """
    users = models.db_session.query(
        models.User
    )

    # Сортировка
    if order_by['field'] not in ['name', 'created']:
        raise ValueError
    if order_by['order'] not in ['asc', 'desc']:
        raise ValueError
    field = getattr(models.User, order_by['field'])
    order = getattr(field, order_by['order'])
    users = users.order_by(
        order()
    )

    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
