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

from . import mutation
from .. import lib, models


def user_as_dict(
    user: models.User,
    fields: list = ['id', 'name']
):
    """Пользователя как словарь (в JSON)
    """
    def field_favorite():
        # Избранное
        assert lib.get_user(), 'favorite only authorized users'
        result = False
        favorite = models.db_session.query(
            models.PageFavorite
        ).filter(
            models.PageFavorite.user_id == user.id,
            models.PageFavorite.user_id == lib.get_user().id
        ).first()
        if favorite:
            result = True
        return result

    def field_tags(fields: list=['id', 'name']):
        # Теги
        result = []
        for relation in user.tags:
            response = tag_as_dict(relation.tag, fields)
            result.append(response)
        return result

    funcs = {
        'favorite': field_favorite,
        'tags': field_tags
    }
    result = {}

    for column in user.__table__.columns:
        if column.name in fields:
            if column.name not in ['password']:
                result[column.name] = getattr(user, 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
