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

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


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

    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('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) -> list:
    """Список заметок
    """
    notes = models.db_session.query(
        models.Note
    ).order_by(
        models.Note.title.asc()
    )
    notes = lib.getpage(
        notes,
        page,
        app.config['ITEMS_ON_PAGE']
    ).all()

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


@jsonrpc.method('notes.count')
def notes_count() -> int:
    """Количество заметок
    """
    result = models.db_session.query(
        models.Note
    ).count()
    return result
