#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db.models import Q
from gm_rpcd.all import bind
from gm_types.gaia import (
    REPORT_REASON,
    REPORT_TYPE,
    FILTER_WORD_TYPE
)
from gm_types.error import ERROR as CODES

from talos.models.diary import Diary
from talos.models.topic import Problem, TopicReply
from talos.models.report import Report

from utils.rpc import gen, get_current_user


@bind('topic/report/submit')
def submit_report(reason_id=None, topic_id=None, reply_id=None, diary_id=None):
    user = get_current_user()
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    report = Report()
    report.user_id = user.id

    ruler = Q(user_id=user.id)

    if reply_id:
        reply = TopicReply.objects.get(id=reply_id)
        report.topic_reply = reply
        ruler &= Q(topic_reply=reply)

        if reply.diary:
            # NOTE: currently we cannt report diary, so...
            report.type = REPORT_TYPE.DIARY_REPLY
            ruler &= Q(type=REPORT_TYPE.DIARY_REPLY)

        elif reply.problem:
            report.type = REPORT_TYPE.REPLY
            ruler &= Q(type=REPORT_TYPE.REPLY)

    elif topic_id:
        # 增加对日记本回复的举报 如果有topic_id 是对帖子的举报
        problem = Problem.objects.get(id=topic_id)
        report.problem = problem
        report.type = REPORT_TYPE.TOPIC
        ruler &= Q(problem=problem) & Q(type=REPORT_TYPE.TOPIC)

    elif diary_id:
        diary = Diary.objects.get(id=diary_id)
        report.diary = diary
        report.type = REPORT_TYPE.DIARY
        ruler &= Q(diary=diary) & Q(type=REPORT_TYPE.DIARY)

    else:
        return {'success': False}

    if Report.objects.filter(ruler).count():
        return gen(CODES.ALREADY_REPORTED)

    if str(reason_id) in REPORT_REASON:
        report.reason = reason_id

    report.save()

    return {'success': True}