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

from .. import jsonrpc, login_required
from ... import acl, app, lib, models
from ...mutations.note import note_as_dict


@jsonrpc.method('favorite.note.add')
@login_required
def favorite_note_add(id: int) -> bool:
    """Добавление статьи в избранное
    """
    note = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id
    ).first()
    if note is None:
        raise ValueError
    exist = models.db_session.query(
        models.NoteFavorite
    ).filter(
        models.NoteFavorite.note_id == id,
        models.NoteFavorite.user_id == lib.get_user().id
    ).first()
    if exist:
        raise ValueError

    new_favorite_note = models.NoteFavorite(
        lib.get_user(),
        note
    )
    models.db_session.add(new_favorite_note)
    models.db_session.commit()

    return True


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


@jsonrpc.method('favorite.notes')
@login_required
def favorite_notes(
    page: int = 1,
    order_by: dict = {'field': 'title', 'order': 'asc'},
    fields: list = ['id', 'title']
) -> list:
    indexes = models.db_session.query(
        models.NoteFavorite.note_id
    ).filter(
        models.NoteFavorite.user_id == lib.get_user().id
    )
    notes = models.db_session.query(
        models.Note
    ).filter(
        models.Note.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.Note, order_by['field'])
    order = getattr(field, order_by['order'])
    notes = notes.order_by(
        order()
    )

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

    result = []
    for note in notes:
        newRow = note_as_dict(note, fields)
        result.append(newRow)

    return result


@jsonrpc.method('favorite.notes.count')
@login_required
def favorite_notes_count() -> int:
    result = models.db_session.query(
        models.NoteFavorite
    ).filter(
        models.NoteFavorite.user_id == lib.get_user().id
    ).count()

    return result
