import json
from utils.base import APIView
from utils.logger import error_logger


class ReplyUpdateOrCreateView(APIView):
    def get(self, request):
        topic_id = request.GET.get('topic_id')
        pictorial_id = request.GET.get('pictorial_id')
        offset = int(request.GET.get('page', 0))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))

        if topic_id:
            filter.update({'topic_id': topic_id})
        elif pictorial_id:
            filter.update({'pictorial_id': pictorial_id})

        try:
            data = self.rpc['venus/sun/reply/list'](offset=(offset-1) * limit, limit=limit, filters=filter).unwrap()
        except Exception as e:
            error_logger.error(u'回复帖子失败%s' , e)
            raise
        return data

    def post(self, request):

        reply_ids = json.loads(request.POST.get('reply_ids', []))
        try:
            self.rpc['venus/sun/reply/batch_delete'](ids=reply_ids).unwrap()
        except Exception as e:
            error_logger.error(u'批量更新回复失败%s', e)
            raise
        return {
            'message': '操作成功'
        }


class ReplyCreate(APIView):
    def post(self, request):

        request.POST.get('be_replied_id', None)
        data = {
            'user_id': request.POST.get('user_id').split(':')[0],
            'replied_id': request.POST.get("replied_id", None),
            'content': request.POST.get('content'),
            'replied_user_id': request.POST.get('replied_user_id', None)
        }
        topic_id = request.POST.get('topic_id')
        pictorial_id = request.POST.get('pictorial_id')

        if topic_id:
            data['topic_id'] = topic_id

        if pictorial_id:
            data['pictorial_id'] = pictorial_id

        try:
            data = self.rpc['venus/sun/reply/edit'](id=None, data=data).unwrap()
        except Exception as e:
            error_logger.error(u'编辑评论失败%s', e)
            raise
        return {'data': data}


class ReplyVote(APIView):
    def post(self, request):

        reply_id = int(request.POST.get('reply_id'))
        vote_num = int(request.POST.get('vote_num'))

        try:
            self.rpc['venus/sun/reply/vote'](reply_id=reply_id, vote_num=vote_num).unwrap()
        except Exception as e:
            error_logger.error(u'编辑帖子失败%s', e)
            raise

        return {
            'message': '操作成功'
        }
