__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('page.favorite.add')
@login_required
def page_favorite_add(id: int) -> bool:
    """Добавление статьи в избранное
    """
    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 True


@jsonrpc.method('page.favorite.delete')
@login_required
def page_favorite_delete(id: int) -> bool:
    """Удаление статьи из избранного
    """
    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 True
