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

from . import mutation
from .. import lib, models


def page_as_dict(
    page: models.Page,
    fields: list = ['id', 'title']
):
    """Статью как словарь (в JSON)
    """
    def field_favorite():
        # Избранное
        assert lib.get_user(), 'favorite only authorized users'
        result = False
        favorite = models.db_session.query(
            models.PageFavorite
        ).filter(
            models.PageFavorite.page_id == page.id,
            models.PageFavorite.user_id == lib.get_user().id
        ).first()
        if favorite:
            result = True
        return result

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

    def field_user(fields: list=['id', 'name']):
        # Пользователь
        user_as_dict = mutation['user']
        return user_as_dict(page.user, fields)

    def field_parents(fields: list = ['id', 'title']):
        # Родители
        result = []
        parent = page.parent
        while parent:
            response = page_as_dict(parent, fields)
            result.append(response)
            parent = parent.parent
        result.reverse()
        return result

    def field_nodes(fields: list = ['id', 'title']):
        # Дети
        result = []
        for item in page.nodes:
            response = page_as_dict(item, fields)
            result.append(response)
        return result

    funcs = {
        'favorite': field_favorite,
        'tags': field_tags,
        'user': field_user,
        'parents': field_parents,
        'nodes': field_nodes
    }
    result = {}

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