import attr
from typing import Dict, Iterable, List, Set

from staff.departments.models import Department
from staff.lib.models import roles_chain

from staff.preprofile.models import Preprofile


def _dep_id_to_hrbp_emails(departments: Set[Department]) -> Dict:
    hrbps_lists = roles_chain.get_grouped_hrbp_by_departments(
        department_list=departments,
        fields=['work_email'],
    )
    return {
        dep_id: [it.get('staff__work_email') for it in hrbp_objs]
        for dep_id, hrbp_objs in hrbps_lists.items()
    }


def _dep_id_to_chief_email(departments: Set[Department]) -> Dict:
    chiefs = roles_chain.get_grouped_chiefs_by_departments(
        department_list=departments,
        fields=['work_email'],
    )
    return {
        dep_id: chief_obj.get('staff__work_email')
        for dep_id, chief_obj in chiefs.items()
    }


@attr.s
class PreprofileRemindEmails(object):
    emails: List[str] = attr.ib(factory=list)
    urgent_emails: List[str] = attr.ib(factory=list)


def gather_remind_emails(preprofiles: Iterable[Preprofile]) -> Dict[int, PreprofileRemindEmails]:
    departments = {it.department for it in preprofiles}
    dep_id_to_chief_email = _dep_id_to_chief_email(departments)
    dep_id_to_hrbp_emails = _dep_id_to_hrbp_emails(departments)

    result = {}
    for preprofile in preprofiles:
        department_id = preprofile.department_id

        emails = []
        chief_email = dep_id_to_chief_email[department_id]

        if chief_email:
            emails.append(chief_email)

        if preprofile.recruiter:
            emails.append(preprofile.recruiter.email)

        result[preprofile.id] = PreprofileRemindEmails(
            emails,
            dep_id_to_hrbp_emails.get(department_id, []),
        )

    return result
