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

from .. import jsonrpc, login_required
from ... import acl, app, lib, models
from ...mutations.page import page_as_dict


@jsonrpc.method('favorite.page.add')
@login_required
def favorite_page_add(id: int) -> str:
    """Добавление статьи в избранное
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError
    exist = models.db_session.query(
        models.PageFavorite
    ).filter(
        models.PageFavorite.page_id == id,
        models.PageFavorite.user_id == lib.get_user().id
    ).first()
    if exist:
        raise ValueError

    new_favorite_page = models.PageFavorite(
        lib.get_user(),
        page
    )
    models.db_session.add(new_favorite_page)
    models.db_session.commit()

    return 'ok'


@jsonrpc.method('favorite.page.delete')
@login_required
def favorite_page_delete(id: int) -> str:
    """Удаление статьи из избранного
    """
    exist = models.db_session.query(
        models.PageFavorite
    ).filter(
        models.PageFavorite.page_id == id,
        models.PageFavorite.user_id == lib.get_user().id
    ).first()
    if exist is None:
        raise ValueError
    models.db_session.delete(exist)
    models.db_session.commit()
    return 'ok'


@jsonrpc.method('favorite.pages')
@login_required
def favorite_pages(
    page: int = 1,
    order_by: dict = {'field': 'title', 'order': 'asc'},
    fields: list = ['id', 'title']
) -> list:
    indexes = models.db_session.query(
        models.PageFavorite.page_id
    ).filter(
        models.PageFavorite.user_id == lib.get_user().id
    )
    pages = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id.in_(indexes)
    )

    # Сортировка
    if order_by['field'] not in ['created', 'id', 'title', '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('favorite.pages.count')
@login_required
def favorite_pages_count() -> int:
    result = models.db_session.query(
        models.PageFavorite
    ).filter(
        models.PageFavorite.user_id == lib.get_user().id
    ).count()

    return result
