from staff.gap.workflows.base_workflow import BasePeriodicWorkflow
from staff.gap.workflows.decorators import allowed_states
from staff.gap.workflows.choices import GAP_STATES as GS

from staff.gap.controllers.utils import get_chief


class RemoteWorkWorkflow(BasePeriodicWorkflow):
    workflow = 'remote_work'
    ui_key = 'gap.workflow.remote_work'
    gap_type = 'remote_work'
    verbose_name = 'Удалённая работа'
    verbose_name_en = 'Remote work'
    color = '#008000'

    template_context = {
        'new_gap_head_ru': 'Удалённая работа создана',
        'new_gap_head_en': 'Remote work was created',
        'edit_gap_head_ru': 'Удалённая работа изменена',
        'edit_gap_head_en': 'Remote work was edited',
        'cancel_gap_head_ru': 'Удалённая работа отменена',
        'cancel_gap_head_en': 'Remote work was canceled',
    }

    def _get_approver(self):
        if self.periodic_gap:
            return get_chief(self.periodic_gap['person_login'])
        return get_chief(self.gap['person_login'])

    def new_gap(self, data):
        self._create_self_gap(data)

        self._new_gap_email(approver=self._get_approver())

        return self.gap

    def new_periodic_gap(self, data):
        self._create_self_periodic_gap(data)

        # Возвращаем первый созданный геп, для того что бы фронт мог отрисовать карточку созданного отсутствия
        self._new_periodic_gap_email(approver=self._get_approver())
        return self.gap

    def _append_gap(self, data):
        return {
            'work_in_absence': True,
        }

    @allowed_states([GS.NEW])
    def edit_gap(self, data):
        data['work_in_absence'] = True
        updated = self._update_editable(data, self.editable_fields)
        if not updated:
            return

        self._update()
        if data['is_periodic_gap']:
            return

        self._new_to_notify(updated)

        approver = self._get_approver()
        self._edit_gap_email(updated, approver=approver)

    @allowed_states([GS.NEW])
    def cancel_gap_with_period(self):
        self._set_state_gaps_with_period(GS.CANCELED)

        self._update_periodic_gap()
        self._cancel_periodic_gap_email(approver=self._get_approver())

    @allowed_states([GS.NEW])
    def cancel_gap(self):
        self._set_state(GS.CANCELED)
        self._update()
        approver = self._get_approver()
        self._cancel_gap_email(approver=approver)
