from django.db.models import Q
from gm_types.error import ERROR
from gm_types.mimas import (
    TRACTATE_ID_SOURCE, TRACTATE_REPORT_TYPE, TRACTATE_REPORT_ACTION,
)

from .base import BaseService

from talos.models.tractate import TractateReport

from talos.rpc import gen


class ReportService(BaseService):

    model = TractateReport

    @classmethod
    def create(cls, user_id, reason_id, tractate_id=None, reply_id=None):
        """
         新帖子举报
        :param reason_id:
        :param tractate_id:
        :param reply_id:
        :param user_id:
        :return:
        """
        report = TractateReport()
        report.user_id = user_id
        report.reason = reason_id
        query = Q(user_id=user_id, report_type=TRACTATE_REPORT_TYPE.TRACTATE)

        source_status = TRACTATE_ID_SOURCE.TRACTATE_REPLY if reply_id \
            else TRACTATE_ID_SOURCE.TRACTATE
        query &= Q(source_status=source_status)

        if TractateReport.objects.filter(query).exists():
            return gen(ERROR.ALREADY_REPORTED)

        if reply_id:
            report.source_id = reply_id
            report.source_status = TRACTATE_ID_SOURCE.TRACTATE_REPLY
            report.report_type = TRACTATE_REPORT_TYPE.TRACTATE

        elif tractate_id:
            report.source_id = tractate_id
            report.source_status = TRACTATE_ID_SOURCE.TRACTATE
            report.report_type = TRACTATE_REPORT_TYPE.TRACTATE

        report.save()
