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

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


@jsonrpc.method('page')
def page_id(id: int) -> dict:
    """Статья
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

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


@jsonrpc.method('page.add')
@login_required
def page_add(title: str, body: str) -> dict:
    """Добавление новой статьи
    """
    newPage = models.Page(
        lib.get_user(),
        title
    )
    newPage.body = body
    models.db_session.add(newPage)
    models.db_session.commit()

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


@jsonrpc.method('page.destroy')
@login_required
def page_destroy(id: int) -> bool:
    """Полное уничтожение статьи

    Аргументы:
    id -- ID статьи
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

    models.db_session.delete(page)
    models.db_session.commit()

    return True


@jsonrpc.method('page.update')
@login_required
def page_update(id: int, title: str, text: str) -> dict:
    """Обновить статью
    """
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError

    page.title = title
    page.text = text

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


@jsonrpc.method('pages')
def pages_list(page: int) -> list:
    """Список статей
    """
    pages = models.db_session.query(
        models.Page
    ).order_by(
        models.Page.title.asc()
    )
    pages = lib.getpage(
        pages,
        page,
        app.config['ITEMS_ON_PAGE']
    ).all()

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


@jsonrpc.method('pages.count')
def pages_count() -> int:
    """Общее количество статей
    """
    result = models.db_session.query(
        models.Page
    ).count()
    return result
