import logging

from staff.lib import waffle

from staff.trip_questionary.controller.operations.base import OperationBase, lib
from staff.trip_questionary.controller.notifications import HrMobileNotification
from staff.trip_questionary.controller.context import get_departure_city

logger = logging.getLogger(__name__)


@lib.register
class HRMobile(OperationBase):

    def match_diff_preconditions(self):
        result = (
            not self.TC.is_conf
            and
            self.TC.is_ticket_approved
            and
            self.TC.employee_need_mobile_additional_packages
        )
        if not result and self.TC.employee_need_mobile_additional_packages:
            trip = self.TC.trip
            logger.info(f'For {trip.uuid} of type {trip.data["event_type"]} status is {self.TC.get_status()}')
        return result

    def match_preconditions(self):
        return (
            super(HRMobile, self).match_preconditions()
            or
            self.match_diff_preconditions()
        )

    QUEUE = 'MOBILE'
    TYPE = 'request'
    COMPONENT = 52309
    notification_class = HrMobileNotification

    def run(self):
        """Полезная работа"""
        context = self.get_notification_context()
        notification = self.notification_class(
            trip_uuid=self.trip.uuid,
            context=context,
            is_personal=True,
        )
        params = self.get_send_params()
        issue = notification.send(**params)
        self.employee_data['hr_mobile_issue'] = {'key': issue.key}
        super(HRMobile, self).run()

    def get_notification_context(self):
        ctx = self.trip.data.copy()
        ctx['departure_city'] = get_departure_city(self.trip.data['city_list'])
        ctx['employee_data'] = self.employee_data.copy()
        return ctx

    def get_send_params(self):
        """Возвращает параметры для отправки нотификации."""

        if not waffle.switch_is_active('switch_hr_mobile_tickets_to_mobile_queue'):  # TODO: удалить (см. STAFF-10687)
            self.QUEUE = 'HR'
            self.TYPE = 'task'
            self.COMPONENT = 11286

        params = {
            'author': self.trip.data['author'],
            'unique': self.get_unique(),
            'queue': self.QUEUE,
            'type': self.TYPE,
            'components': [self.COMPONENT],
            'followers': [self.employee_data['employee'].login],
        }
        return params

    def get_unique(self):
        """Вернуть значение unique для создаваемого тикета"""
        return '{uuid}/{login}/hrmobile'.format(
            uuid=self.trip.uuid,
            login=self.employee_data['employee'].login,
        )
