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

from . import mutation
from .. import models


def tag_as_dict(
    tag: models.Tag,
    fields: list = ['id', 'name']
):
    """Тег в словарь
    """
    def field_pages(fields: list = ['id', 'title']):
        # Теги
        page_as_dict = mutation['page']
        result = []
        for page in tag.pages:
            response = page_as_dict(page, fields)
            result.append(response)
        return result

    def field_user(tag):
        # Пользователь
        return tag.user.as_dict()

    funcs = {
        'pages': field_pages,
        'user': field_user,
    }
    result = {}

    for column in tag.__table__.columns:
        if column.name in fields:
            result[column.name] = getattr(tag, column.name)

    for field in fields:
        if isinstance(field, dict):
            for key in field:
                if key in funcs:
                    func = funcs[key]
                    result[key] = func(field[key])
        else:
            if field in funcs:
                func = funcs[field]
                result[field] = func()

    return result
