import logging

from django.views.decorators.http import require_GET

from staff.lib.decorators import responding_json, available_for_external
from staff.lib.models.roles_chain import get_grouped_chiefs_by_departments

from staff.preprofile.repository import Repository

logger = logging.getLogger(__name__)


@require_GET
@responding_json
@available_for_external('preprofile.available_preprofile_for_externals')
def cab_export(request):
    mptt_keys = [
        'department__id',
        'department__tree_id',
        'department__lft',
        'department__rght',
    ]
    fields_to_response = [
        'id',
        'first_name',
        'last_name',
    ]
    all_fields = mptt_keys + fields_to_response

    cur_person = request.user.staff

    preprofiles = (
        Repository(cur_person)
        .preprofiles_waiting_chief_to_confirm()
        .values(*all_fields)
        .order_by('-join_at')
    )
    departments = {
        item['department__id']: {
            key.replace('department__', ''): item[key]
            for key in mptt_keys
        }
        for item in preprofiles
    }
    dep_id_to_chief = get_grouped_chiefs_by_departments(departments.values(), fields=['id'])
    departments_directly_ruled = {
        dep_id for dep_id, chief in dep_id_to_chief.items()
        if cur_person.id == chief['staff__id']
    }
    res = [
        {field: item[field] for field in fields_to_response}
        for item in preprofiles
        if item['department__id'] in departments_directly_ruled
    ]
    return {'preprofiles': res}
