import math

from django.utils.translation import get_language

from staff.lib.utils.qs_values import extract_related, localize

from staff.person_profile.controllers.search import (
    self_page_re,
    get_person,
)
from staff.person.models import MemorialProfile
from staff.departments.models import DepartmentStaff
from staff.departments.utils import get_department_chain
from staff.gap.workflows.utils import find_workflows_by_lang

import logging
logger = logging.getLogger('staff.gap.controllers.meta')


def _prepare_person(person):
    if not person:
        return

    person = localize(person)
    can_show_name = not person['is_dismissed'] or person['extra__staff_agreement']
    result = {
        'id': person['id'],
        'login': person['login'],
        'first_name': person['first_name'] if can_show_name else None,
        'last_name': person['last_name'] if can_show_name else None,
        'is_robot': person['is_robot'],
        'is_dismissed': person['is_dismissed'],
        'is_homeworker': person['is_homeworker'],
        'is_memorial': _is_memorial(person['id']),
        'country_id': person['organization__city__country_id'],
        'work_mode': person['work_mode'],
    }
    if get_language() != 'ru':
        del person['middle_name']

    department = extract_related(person, 'department')
    dep_chain = get_department_chain(**department)

    result['department_chain'] = [localize(d) for d in dep_chain]
    result['department_roles'] = [
        value for value in
        DepartmentStaff.objects
        .filter(staff_id=person['id'])
        .values('role', 'department__url')
    ]

    if person['vacation'] is not None:
        result['vacation'] = math.floor(person['vacation'])
    else:
        result['vacation'] = None

    return result


def find_person(login, observer_login):
    fields = [
        'id',
        'login',
        'first_name',
        'last_name',
        'middle_name',
        'first_name_en',
        'last_name_en',
        'department__lft',
        'department__rght',
        'department__tree_id',
        'department__id',
        'organization__city__country_id',
        'organization__country_code',
        'vacation',
        'is_robot',
        'is_dismissed',
        'is_homeworker',
        'extra__staff_agreement',
        'work_mode',
    ]

    has_tilda = login.startswith('~')
    if has_tilda:
        login = login[1:]

    if observer_login == login:
        if has_tilda:
            login = ''
        else:
            return _prepare_person(get_person(observer_login, fields))

    if self_page_re.match(login):
        return _prepare_person(get_person(observer_login, fields))

    try:
        return _prepare_person(get_person(login, fields))
    except IndexError:
        return None


def _is_memorial(person_id):
    return MemorialProfile.objects.filter(person_id=person_id).exists()


def get_calendar_legend():
    workflows = find_workflows_by_lang(get_language())
    return [{
        'type': workflow.workflow,
        'ui_key': workflow.ui_key,
    } for workflow in workflows]


def get_subscriptions():
    pass


def get_tabs_flags():
    pass
