from intranet.femida.src.api.core.serializers import IdNameSerializer
from intranet.femida.src.notifications.base import R, FetchingNotificationBase
from intranet.femida.src.notifications.headers import (
    get_application_headers,
    get_candidate_headers_prefetched,
    get_vacancy_headers_prefetched,
)
from intranet.femida.src.notifications.utils import (
    get_candidate_message_id,
    get_candidate_email_subject,
    get_application_email_subject,
)

from . import serializers


reminder_user = R(lambda x: [x.instance.user])


class ReminderBaseNotification(FetchingNotificationBase):

    receivers = reminder_user

    @property
    def candidate(self):
        return self.instance.message.candidate

    @property
    def application(self):
        return self.instance.message.application

    def get_thread_id(self):
        return get_candidate_message_id(self.candidate)

    def get_common_context(self):
        attachments = self.instance.message.attachments.all()
        context = super().get_common_context()
        context['message'] = serializers.MessageSerializer(self.instance.message).data
        context['attachments'] = IdNameSerializer(attachments, many=True).data
        context['candidate'] = serializers.CandidateSerializer(self.candidate).data
        return context

    def get_femida_headers(self):
        headers = self.get_default_femida_headers()
        headers.update(get_candidate_headers_prefetched(self.candidate))
        return headers


class NoteReminderNotification(ReminderBaseNotification):

    subject_prefix = 'Напоминание о заметке'
    template_name = 'mail/reminders/note-reminder.html'
    event_type = 'candidate_note_remind'

    def get_subject(self):
        return get_candidate_email_subject(self.candidate, self.subject_prefix)


class InternalMessageReminderNotification(ReminderBaseNotification):

    subject_prefix = 'Напоминание о комментарии'
    template_name = 'mail/reminders/comment-reminder.html'
    event_type = 'application_message_remind'

    def get_subject(self):
        return get_application_email_subject(self.application, self.subject_prefix)

    def get_common_context(self):
        context = super().get_common_context()
        context['application'] = serializers.ApplicationSerializer(self.application).data
        context['vacancy'] = serializers.VacancySerializer(self.application.vacancy).data
        return context

    def get_femida_headers(self):
        headers = super().get_femida_headers()
        headers.update(get_application_headers([self.application.id]))
        headers.update(get_vacancy_headers_prefetched([self.application.vacancy]))
        return headers
