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

from .. import jsonrpc, login_required
from ... import app, lib, models
from ...mutations import mutation


page_as_dict = mutation['page']


@jsonrpc.method('page')
def page_id(
    id: int,
    fields: list = ['id', 'title']
) -> dict:
    """Статья
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

    result = page_as_dict(page, fields)
    return result


@jsonrpc.method('page.add')
@login_required
def page_add(title: str, body: str) -> dict:
    """Добавление новой статьи
    """
    newPage = models.Page(
        lib.get_user(),
        title
    )
    newPage.body = body
    models.db_session.add(newPage)
    models.db_session.commit()

    result = newPage.as_dict()
    result['user'] = newPage.user.as_dict()
    result['tags'] = []
    return result


@jsonrpc.method('page.destroy')
@login_required
def page_destroy(id: int) -> bool:
    """Полное уничтожение статьи

    Аргументы:
    id -- ID статьи
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

    models.db_session.delete(page)
    models.db_session.commit()

    return True


@jsonrpc.method('page.update')
@login_required
def page_update(id: int, title: str, body: str) -> dict:
    """Обновить статью
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

    page.title = title
    page.body = body
    models.db_session.commit()

    result = page_as_dict(page)
    return result


@jsonrpc.method('pages')
def pages_list(
    page: int = 1,
    order_by: dict = {'field': 'title', 'order': 'asc'},
    fields: list = ['id', 'title'],
) -> list:
    """Список статей
    """
    pages = models.db_session.query(
        models.Page
    )

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

    pages = lib.getpage(
        pages,
        page,
        app.config['ITEMS_ON_PAGE']
    ).all()

    result = []
    for page in pages:
        newRow = page_as_dict(page, fields)
        result.append(newRow)
    return result


@jsonrpc.method('pages.count')
def pages_count() -> int:
    """Общее количество статей
    """
    result = models.db_session.query(
        models.Page
    ).count()
    return result
