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

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


@jsonrpc.method('tag.page.add')
@login_required
def tag_page_add(tag: int, id: int) -> dict:
    """Добавление тега на страницы
    """
    tagRow = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == tag
    ).first()
    if tagRow is None:
        raise ValueError
    page = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id == id
    ).first()
    if page is None:
        raise ValueError
    exist = models.db_session.query(
        models.PageTag
    ).filter(
        models.PageTag.tag_id == tagRow.id,
        models.PageTag.page_id == page.id
    ).first()
    if exist:
        raise ValueError
    newtagpage = models.PageTag(
        page,
        tagRow
    )
    models.db_session.add(newtagpage)
    models.db_session.commit()
    result = tagRow.as_dict()
    return result


@jsonrpc.method('tag.page.delete)')
@login_required
def tag_page_delete(tag: int, id: int) -> bool:
    """Удаление тега со страницы
    """
    exist = models.db_session.query(
        models.PageTag
    ).filter(
        models.PageTag.tag_id == tag,
        models.PageTag.page_id == id
    ).first()
    if exist is None:
        raise ValueError
    models.db_session.delete(exist)
    models.db_session.commit()
    return True


@jsonrpc.method('tag.pages')
def tag_pages_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.PageTag.page_id
    ).filter(
        models.PageTag.tag_id == id
    )
    pages = models.db_session.query(
        models.Page
    ).filter(
        models.Page.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.Page, order_by['field'])
    order = getattr(field, order_by['order'])
    pages = pages.order_by(
        order()
    )

    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('tag.pages.count')
def tag_pages_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.PageTag.page_id
    ).filter(
        models.PageTag.tag_id == id
    )
    result = models.db_session.query(
        models.Page
    ).filter(
        models.Page.id.in_(indexes)
    ).count()
    return result
