import yenv

from django.template import Template

from staff.gap.controllers.email_ctl import EmailCtl
from staff.gap.controllers.mail_to_send import EmailToSendCtl
from staff.gap.controllers.templates import get_templates_by_logins, PeriodicGapTemplateContext


def _skip_for_ruby_crown_owner(action):
    """Не выполняем действие для владельцев рубиновой коронки"""
    def checked(self, *args, **kwargs):
        if self.person['is_ruby_crown_owner']:
            return None
        return action(self, *args, **kwargs)
    return checked


class EmailMixin(object):

    @_skip_for_ruby_crown_owner
    def _new_gap_email(self, approver=None):
        """
        :param approver: dict with id, login and work_email fields from Staff model
        :type approver: dict
        """
        EmailCtl(data=self.gap, approver=approver).notify(
            person=self.person,
            modifier=self.modifier,
            workflow=self.workflow,
            tag='new_gap',
        )

    @_skip_for_ruby_crown_owner
    def _new_periodic_gap_email(self, approver=None):
        """
        :param approver: dict with id, login and work_email fields from Staff model
        :type approver: dict
        """
        EmailCtl(
            data=self.periodic_gap,
            approver=approver,
            context_template_cls=PeriodicGapTemplateContext,
        ).notify(
            person=self.person,
            modifier=self.modifier,
            workflow=self.workflow,
            tag='new_periodic_gap',
        )

    @_skip_for_ruby_crown_owner
    def _edit_gap_email(self, updated, approver=None):
        if updated:
            EmailCtl(data=self.gap, approver=approver).notify(
                person=self.person,
                modifier=self.modifier,
                workflow=self.workflow,
                tag='edit_gap',
                gap_diff=updated,
            )

    @_skip_for_ruby_crown_owner
    def _cancel_gap_email(self, approver=None):
        EmailCtl(data=self.gap, approver=approver).notify(self.person, self.modifier, self.workflow, 'cancel_gap')

    @_skip_for_ruby_crown_owner
    def _cancel_periodic_gap_email(self, approver=None):
        EmailCtl(
            data=self.periodic_gap,
            approver=approver,
            context_template_cls=PeriodicGapTemplateContext,
        ).notify(
            self.person,
            self.modifier,
            self.workflow,
            tag='cancel_periodic_gap',
        )

    @_skip_for_ruby_crown_owner
    def _move_mandatory_vacation_email(self, approver=None):
        EmailCtl(
            data=self.gap,
            approver=approver,
        ).notify(
            self.person,
            self.modifier,
            self.workflow,
            tag='move_mandatory_vacation',
        )

    def _new_to_notify(self, updated):
        if 'to_notify' in updated:
            values = updated['to_notify']
            to_notify_diff = set(values['new']) - set(values['old'])
            if to_notify_diff:
                EmailCtl(
                    data=self.gap,
                    send_not_self=False,
                    include_subscribers=False,
                ).notify(self.person, self.modifier, self.workflow, 'new_gap', to_notify_overwrite=to_notify_diff)
            del updated['to_notify']

    @_skip_for_ruby_crown_owner
    def deffer_finish_reminder(self):
        person_login = self.gap['person_login']
        workflow = self.gap['workflow']
        tag = 'finish_reminder'
        t_data = get_templates_by_logins([person_login], 'email', workflow, tag)[person_login]
        if t_data['template']:
            context = self._get_gap_context({})
            recipients = [self.person['work_email']]

            if yenv.type != 'production':
                context['original_emails'] = recipients

            EmailToSendCtl().new(
                self.gap['id'],
                recipients,
                Template(t_data['template']['template']).render(context),
                workflow,
                tag,
            )
            self.gap['sent_aftertrip_reminder'] = True
            self._update()
