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

from .. import jsonrpc, login_required
from ... import models
from ...mutations.tag import tag_as_dict


@jsonrpc.method('tag')
def tag_id(
    id: int,
    fields: list = ['id', 'name']
) -> dict:
    """Тег
    """
    tag = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == id
    ).first()
    if tag is None:
        raise ValueError

    result = tag_as_dict(tag, fields)
    return result


@jsonrpc.method('tag.add')
@login_required
def tag_add(name: str) -> dict:
    """Добавить новый тег
    """
    exist = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.name == name
    ).first()
    if exist:
        raise ValueError

    newTag = models.Tag(name)
    models.db_session.add(newTag)
    models.db_session.commit()
    return newTag.as_dict()


@jsonrpc.method('tag.delete')
@login_required
def tag_delete(id: int) -> bool:
    """Удалить тег
    """
    exist = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.id == id
    ).first()
    if exist is None:
        raise ValueError

    models.db_session.delete(exist)
    models.db_session.commit()
    return True


@jsonrpc.method('tag.exist')
def tag_exist(name: str) -> dict:
    """Проверить существует ли тег и вернуть информацию о нём
    """
    text = name.lower().strip()
    tagRow = models.db_session.query(
        models.Tag
    ).filter(
        models.Tag.name == text
    ).first()
    if tagRow is None:
        raise ValueError
    result = {
        'id': tagRow.id,
        'name': tagRow.name
    }
    return result


@jsonrpc.method('tags')
def tags_list() -> list:
    """Список тегов
    """
    tags = models.db_session.query(
        models.Tag
    ).all()

    result = []
    for tag in tags:
        newRow = tag.as_dict()
        result.append(newRow)
    return result


@jsonrpc.method('tags.groups')
def tags_groups() -> dict:
    """Облако тегов
    """
    tags = models.db_session.query(
        models.Tag
    ).order_by(
        models.Tag.name
    ).all()
    result = {}
    for tag in tags:
        tag_json = tag.as_dict()
        if tag.name[0] in result:
            result[tag.name[0]].append(tag_json)
        else:
            result[tag.name[0]] = [tag_json]
    return result
