# -*- coding: UTF-8 -*-

from django.db.models import Q
from community.models import Article

from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from hera.queries.article import ArticleDQ
from hera.utils import model_edit


uri_pre = 'hera/community'


@bind_context(uri_pre+'/get')
def article_get(ctx, article_id, options=None):
    try:
        article = Article.objects.get(id=article_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    article_data = to_dict(article, **options)
    article_data['topic'] = article.topic_id
    return article_data


@bind_context(uri_pre + '/recommend_query')
def recommmend_query(ctx, options):
    dqobj = ArticleDQ(init_q=Q(type=0))
    return dqobj.process(**options)


@bind_context(uri_pre + '/gossip_query')
def gossip_query(ctx, options):
    dqobj = ArticleDQ(init_q=Q(type=1))
    return dqobj.process(**options)


@bind_context(uri_pre+'/edit')
def article_edit(ctx, article_id=None, article_info=None):
    if article_info is None:
        return None

    article_info['topic_id'] = article_info.pop('topic')
    article = model_edit(Article, article_id, article_info)
    return article.id
