from django.http import HttpResponseRedirect
from django.views.decorators.http import require_GET
from django.db import connections, router

from staff.departments.models import Department

from staff.lib.models.roles_chain import chiefs_chain_for_person
from staff.lib.decorators import available_for_external


def _extract_survey_id(request_data, person):
    survey_en_id = request_data.get('survey_en_id', '0')
    survey_ru_id = request_data.get('survey_ru_id', '0')
    survey_id = survey_en_id if person.lang_ui == 'en' else survey_ru_id
    return survey_id


@require_GET
@available_for_external
def with_chief(request):
    """Ручка редиректит на опрос с заполненным логином руководителя."""
    person = request.user.get_profile()
    survey_id = _extract_survey_id(request.GET, person)
    host = request.GET.get('host', 'forms.yandex.net')
    utm_source = request.GET.get('utm_source', 'unknown')

    chiefs_chain = chiefs_chain_for_person(person, fields=['login'])
    chief_login = chiefs_chain[0]['login'] if chiefs_chain else ''

    redirection_url = f'https://{host}/surveys/{survey_id}/?chief={chief_login}&utm_source={utm_source}'

    return HttpResponseRedirect(redirect_to=redirection_url)


@require_GET
@available_for_external
def with_department(request):
    """Ручка редиректит на опрос с заполненным подразделлением."""
    persons_limit = int(request.GET.get('persons_limit', 30))
    host = request.GET.get('host', 'forms.yandex.net')
    utm_source = request.GET.get('utm_source', 'unknown')

    person = request.user.get_profile()

    survey_id = _extract_survey_id(request.GET, person)

    ancestors_sql, params = (
        person.department
        .get_ancestors(include_self=True)
        .values('id')
        .query.sql_with_params()
    )

    sql = f"""
        SELECT dep.url, COUNT(intranet_staff.id)
        FROM intranet_department AS dep
        INNER JOIN intranet_department AS p_dep ON (
            dep.id in ({ancestors_sql})
            AND dep.lft <= p_dep.lft
            AND dep.rght >= p_dep.rght
            AND dep.tree_id = p_dep.tree_id
        )
        INNER JOIN intranet_staff ON (
            intranet_staff.department_id = p_dep.id
            AND intranet_staff.is_dismissed = FALSE
        )
        GROUP BY dep.url, dep.level
        ORDER BY dep.level DESC;
    """

    with connections[router.db_for_read(Department)].cursor() as cursor:
        cursor.execute(sql, params)
        dep_urls = [(d[0], d[1]) for d in cursor.fetchall()]
    dep_url = dep_urls[0][0]
    for d_url, qty in dep_urls:
        if qty >= persons_limit:
            dep_url = d_url
            break

    redirection_url = f'https://{host}/surveys/{survey_id}/?department={dep_url}&utm_source={utm_source}'

    return HttpResponseRedirect(redirect_to=redirection_url)
