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

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


note_as_dict = mutation['note']


@jsonrpc.method('note')
def note_id(
    id: int,
    fields: list[str] = ['id', 'title']
) -> dict:
    """Заметка
    """
    note = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id
    ).first()
    if note is None:
        raise ValueError

    result = note_as_dict(note, fields)
    return result


@jsonrpc.method('note.add')
@login_required
def note_add(title: str, body: str) -> dict:
    """Добавление новой заметки
    """
    newNote = models.Note(
        lib.get_user(),
        title
    )
    newNote.body = body
    models.db_session.add(newNote)
    models.db_session.commit()

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


@jsonrpc.method('note.destroy')
@login_required
def note_destroy(id: int) -> bool:
    """Полное уничтожение заметки

    Аргументы:
    id -- ID заметки
    """
    note = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id
    ).first()
    if note is None:
        raise ValueError

    models.db_session.delete(note)
    models.db_session.commit()

    return True


@jsonrpc.method('note.update')
@login_required
def note_update(id: int, title: str, body: str) -> dict:
    """Обновить заметку
    """
    note = models.db_session.query(
        models.Note
    ).filter(
        models.Note.id == id
    ).first()
    if note is None:
        raise ValueError

    note.title = title
    note.body = body

    result = note.as_dict()
    result['user'] = note.user.as_dict()
    result['tags'] = []
    for tagLink in note.tags:
        result['tags'].append(tagLink.tag.as_dict())
    return result


@jsonrpc.method('notes')
def notes_list(
    page: int = 1,
    order_by: dict = {'field': 'title', 'order': 'asc'},
    fields: list = ['id', 'title']
) -> list:
    """Список заметок
    """
    notes = models.db_session.query(
        models.Note
    ).filter(
        models.Note.user_id==lib.get_user().id
    )

    # Сортировка
    if order_by['field'] not in ['created', 'id', 'title', 'status', '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('notes.count')
def notes_count() -> int:
    """Количество заметок
    """
    result = models.db_session.query(
        models.Note
    ).count()
    return result
