from staff.preprofile.controllers.adopt_controller import AdoptController
from staff.preprofile.controller_behaviours import AbstractBehaviour
from staff.preprofile.forms import EmployeeForm, EmployeeEditForm
from staff.preprofile.models import PREPROFILE_STATUS, FORM_TYPE, EMAIL_DOMAIN
from staff.preprofile.utils import launch_person_avatar_task


class EmployeeBehaviour(AbstractBehaviour):
    def create_form(self, action_context, data=None):
        return EmployeeForm(data=data)

    def create_edit_form(self, action_context, initial_data, data=None):
        return EmployeeEditForm(initial=initial_data, data=data, base_initial={'action_context': action_context})

    def actions_on_create(self):
        raise NotImplementedError()

    def actions_on_edit(self, action_context):
        adopt_controller = AdoptController(action_context)
        preprofile = action_context.preprofile

        if preprofile.status == PREPROFILE_STATUS.NEW:
            return {'save': True, 'approve': True, 'adopt': False, 'create_link': False}
        elif preprofile.status == PREPROFILE_STATUS.APPROVED:
            return {
                'save': adopt_controller.user_has_right_to_adopt(),
                'approve': False,
                'adopt': False,
                'create_link': False,
            }
        elif preprofile.status == PREPROFILE_STATUS.READY:
            editing_by_recruiter = action_context.requested_by == preprofile.recruiter
            return {
                'save': editing_by_recruiter or adopt_controller.user_has_right_to_adopt(),
                'approve': False,
                'adopt': adopt_controller.user_can_adopt(),
                'create_link': False,
            }
        else:
            return {'save': False, 'approve': False, 'adopt': False, 'create_link': False}

    def form_type(self):
        return FORM_TYPE.EMPLOYEE

    def on_new_model(self, action_context):
        action_context.preprofile.need_vpn = True
        action_context.preprofile.need_chair = False
        action_context.preprofile.email_domain = EMAIL_DOMAIN.YANDEX_TEAM_RU

    def is_editable(self):
        return True

    def is_cancelable(self):
        return False

    def is_prepareable(self):
        return False

    def is_approvable(self, action_context):
        return True  # Depends only on status which already checked on controller

    def on_after_create(self, action_context):
        launch_person_avatar_task(task_kwargs={'preprofile_ids': [action_context.preprofile.id]})

    def on_after_change(self, action_context):
        pass


AbstractBehaviour.register(EmployeeBehaviour)
