import logging

from intranet.femida.src.comments.controllers import update_or_create_comment
from intranet.femida.src.core.workflow import Action, Workflow
from intranet.femida.src.problems.choices import COMPLAINT_KINDS, COMPLAINT_RESOLUTIONS
from intranet.femida.src.problems.complaints.controllers import close_complaint


logger = logging.getLogger(__name__)


class ComplaintActionBase(Action):

    def has_permission(self):
        return (
            self.instance.is_active
            and self.user.is_moderator
        )


class CloseActionBase(ComplaintActionBase):

    resolution = ''

    def perform(self, **params):
        instance = close_complaint(
            instance=self.instance,
            initiator=self.user,
            resolution=self.resolution,
        )
        self.extra_data['related_complaints'] = [instance]
        return instance


class RejectAction(CloseActionBase):

    resolution = COMPLAINT_RESOLUTIONS.rejected


class ResolveAction(CloseActionBase):

    resolution = COMPLAINT_RESOLUTIONS.resolved


class MergeProblemsAction(ComplaintActionBase):

    def has_permission(self):
        return (
            super().has_permission()
            and self.instance.kind == COMPLAINT_KINDS.duplicate
        )

    def perform(self, **params):
        """
        Сам экшн ничего не делает,
        нужен только для вычисления доступности мержа задач.
        """
        return self.instance


class CommentAddAction(Action):

    def perform(self, **params):
        params['related_object'] = self.instance
        return update_or_create_comment(params, self.user)


class ComplaintWorkflow(Workflow):

    ACTION_MAP = {
        'reject': RejectAction,
        'resolve': ResolveAction,
        'merge_problems': MergeProblemsAction,
        'comment_add': CommentAddAction,
    }
