from staff.person.models import Organization
from staff.map.models import Office

from django.views.decorators.http import require_http_methods
from django.db.models import Count

from staff.lib.decorators import responding_json, use_request_lang, available_for_external
from staff.lib.utils.qs_values import localize, extract_related


def get_organizations():
    qs = (
        Organization.objects
        .active()
        .values('id', 'name', 'name_en', 'filter_id')
        .filter(staff__is_dismissed=False)
        .annotate(members_count=Count('staff'))
        .order_by('position')
    )
    return [localize(org) for org in qs]


def get_offices():
    qs = (
        Office.objects
        .active()
        .values(
            'id',
            'name',
            'name_en',
            'filter_id',
            'city__id',
            'city__name',
            'city__name_en',
            'city__country__id',
            'city__country__name',
            'city__country__name_en'
        )
        .filter(staff__is_dismissed=False)
        .annotate(members_count=Count('staff'))
        .order_by('city__country', 'city', 'position')
    )

    result = []
    cur_country = None
    cur_city = None

    for office in qs:
        office = localize(office)
        city = extract_related(office, 'city')
        country = extract_related(city, 'country')

        if cur_country is None or cur_country['id'] != country['id']:
            cur_country = country
            cur_country['members_count'] = 0
            result.append(cur_country)

        if cur_city is None or cur_city['id'] != city['id']:
            cur_city = city
            cur_city['members_count'] = 0
            cur_country.setdefault('cities', []).append(cur_city)

        cur_city.setdefault('offices', []).append(office)
        cur_city['members_count'] += office['members_count']
        cur_country['members_count'] += office['members_count']

    return result


@responding_json
@require_http_methods(['GET'])
@use_request_lang
@available_for_external('preprofile.available_preprofile_for_externals')
def orgsoffices(request):
    return {
        'organizations': get_organizations(),
        'countries': get_offices(),
    }
