from staff.lib.exceptions import ErrorWithStatusCode

from staff.person.models import Staff

from staff.emails.models import EmailRedirection
from staff.lib.utils.qs_values import localize
from staff.person_profile.errors import log_does_not_exist_staff_login

import logging
logger = logging.getLogger('person_profile.controllers.redirection')


class RedirectionError(ErrorWithStatusCode):
    pass


def get_initial(login):
    # В природе есть EmailRedirectionController().get_for_reciever(staff)
    # Но он выгребает весь объект Staff, а не только лишь нужныеi values
    redirections = (
        Staff.objects
        .values(
            'id',
            'login',
            'first_name',
            'last_name',
            'first_name_en',
            'last_name_en',
        )
        .filter(emailredirections_from__to_person__login=login)
    )
    return [localize(redirection) for redirection in redirections]


def clean(login, redirection_ids):
    with log_does_not_exist_staff_login(logger=logger, message_params=[login], raise_e=RedirectionError):
        to_person_id = (
            Staff.objects
            .values_list('id', flat=True)
            .get(login=login)
        )

    ids_to_remove = list(set(
        (
            EmailRedirection.objects
            .values_list('from_person_id', flat=True)
            .filter(to_person_id=to_person_id)
        )
    ) - set(redirection_ids))

    EmailRedirection.objects.filter(
        to_person_id=to_person_id,
        from_person_id__in=ids_to_remove
    ).delete()
