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

from rpc.decorators import bind_context
from talos.models.topic import TopicReply, ReplyHeadline
from hera.queries.talos.topicreply import TopicReplyDQ
from services.talos_service import topic_reply_update_reply_num_by_ids

uri_pre = 'hera/topicreply'


@bind_context(uri_pre + '/query')
def topicreply_query(ctx, options):
    dqobj = TopicReplyDQ()
    return dqobj.process(**options)


# comment - zhongchengyang 20170817
# @bind_context(uri_pre + '/list')
# def topicreply_datatable(ctx, req_data):
#     dtobj = TopicReplyDT(TopicReply)
#     return dtobj.process(req_data)


@bind_context(uri_pre + '/headupdate')
def head_update(ctx, items):
    info = [obj['key'] for obj in items]
    for obj in items:
        if obj['headline']:
            try:
                reply = TopicReply.objects.get(id=obj['key'])
                ReplyHeadline.objects.get_or_create(reply=reply)
            except TopicReply.DoesNotExist:
                continue
        else:
            ReplyHeadline.objects.filter(reply_id=obj['key']).delete()
    return info


@bind_context(uri_pre + '/listupdate')
def list_update(ctx, items):
    info = [obj['key'] for obj in items]
    online_ids = []
    not_online_ids = []
    for obj in items:
        topic_reply = TopicReply.objects.get(id=obj['key'])
        if topic_reply.is_online != obj['is_online']:
            # topic_reply.update_reply_num(is_online=obj['is_online'])
            if obj['is_online']:
                online_ids.append(topic_reply.id)
            else:
                not_online_ids.append(topic_reply.id)
        topic_reply.is_online = obj['is_online']
        topic_reply.save()
    topic_reply_update_reply_num_by_ids(ids=online_ids, is_online=True)
    topic_reply_update_reply_num_by_ids(ids=not_online_ids, is_online=False)
    return info
