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

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


@jsonrpc.method('tag.note.add')
@login_required
def tag_note_add(tag: int, id: int) -> dict:
    """Добавление тега в заметку
    """
    noteRow = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id,
        models.Note.user_id == lib.get_user().id
    ).first()
    if noteRow is None:
        raise ValueError
    tagRow = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == tag
    ).first()
    if tagRow is None:
        raise ValueError
    exist = models.db_session.query(
        models.NoteTag
    ).filter(
        models.NoteTag.tag_id == tagRow.id,
        models.NoteTag.note_id == noteRow.id
    ).first()
    if exist:
        raise ValueError
    newtagNote = models.NoteTag(
        noteRow,
        tagRow
    )
    models.db_session.add(newtagNote)
    models.db_session.commit()
    result = tagRow.as_dict()
    return result


@jsonrpc.method('tag.note.delete')
@login_required
def tag_note_delete(tag: int, id: int) -> bool:
    """Удаление тега из заметки
    """
    noteRow = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id,
        models.Note.user_id == lib.get_user().id
    ).first()
    if noteRow is None:
        raise ValueError
    tagRow = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == tag
    ).first()
    if tagRow is None:
        raise ValueError
    exist = models.db_session.query(
        models.NoteTag
    ).filter(
        models.NoteTag.tag_id == tag,
        models.NoteTag.note_id == id
    ).first()
    if exist is None:
        raise ValueError
    models.db_session.delete(exist)
    models.db_session.commit()
    return True


@jsonrpc.method('tag.notes')
@login_required
def tag_notes_list(
    id: int,
    page: int = 1,
    order_by: dict = {'field': 'title', 'order': 'asc'},
    fields: list = ['id', 'title', 'tags', 'user']
) -> list:
    """Список заметок
    """
    tag = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == id
    ).first()
    if tag is None:
        raise ValueError
    indexes = models.db_session.query(
        models.NoteTag.note_id
    ).filter(
        models.NoteTag.tag_id == id
    )
    notes = models.db_session.query(
        models.Note
    ).filter(
        models.Note.user_id == lib.get_user().id,
        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('tag.notes.count')
@login_required
def tag_notes_count(id: int) -> int:
    """Общее количество заметок
    """
    tag = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == id
    ).first()
    if tag is None:
        raise ValueError
    indexes = models.db_session.query(
        models.NoteTag.note_id
    ).filter(
        models.NoteTag.tag_id == id
    )
    result = models.db_session.query(
        models.Note
    ).filter(
        models.Note.user_id == lib.get_user().id,
        models.Note.id.in_(indexes)
    ).count()
    return result
