from pytz import timezone
from django.conf import settings

from staff.departments.utils import get_department_chain
from staff.dismissal.permissions import DismissalPerms
from staff.lib.utils.qs_values import localize
from staff.map.models import Table


def get_checkpoint_dict(checkpoint, requested_by):
    fields = (
        'id',
        'name',
        'name_en',
        'description',
        'description_en',
        'checked',
        'checked_at',
        'checked_by',
    )
    result = localize({field: getattr(checkpoint, field) for field in fields})

    if result['checked_by']:
        result['checked_by'] = localize_staff(result['checked_by'])

    result['disabled'] = result['checked'] or not DismissalPerms.can_check(subject=requested_by, checkpoint=checkpoint)
    return result


def person_location(person):
    result_dict = {}
    try:
        table = (
            Table.objects
            .select_related('floor__office')
            .get(id=person.table_id)
        )
        result_dict['table'] = {
            'id': table.id
        }
        result_dict['floor'] = {
            'id': table.floor_id,
            'name': localize(table.floor.__dict__)['name']
        }
    except Table.DoesNotExist:
        result_dict['table'] = None
        result_dict['floor'] = None

    if person.office:
        result_dict['office'] = {
            'id': person.office_id,
            'name': localize(person.office.__dict__)['name']
        }
    else:
        result_dict['office'] = None

    department = person.department
    department_data = {
        'tree_id': department.tree_id,
        'lft': department.lft,
        'rght': department.rght,
    }

    result_dict['department_chain'] = [
        localize(d) for d in get_department_chain(**department_data)]

    return result_dict


def localize_staff(person):
    data = {
        'id': person.id,
        'login': person.login,
        'first_name': person.first_name,
        'last_name': person.last_name,
        'first_name_en': person.first_name_en,
        'last_name_en': person.last_name_en,
    }
    return localize(data)


def to_tz(data_dict, tz):

    server_tzinfo = timezone(settings.TIME_ZONE)

    def normalized_dt(dt):
        localized_dt = server_tzinfo.localize(dt)
        normailzed = tz.normalize(localized_dt).replace(tzinfo=None)

        return {'date': normailzed.date(), 'time': normailzed.time()}

    if 'checkpoints' in data_dict:
        for cp in data_dict['checkpoints']:
            if cp['checked_at']:
                cp['checked_at'] = normalized_dt(cp['checked_at'])

    if 'completed' in data_dict:
        data_dict['completed']['checked_at'] = normalized_dt(
            data_dict['completed']['checked_at']
        )

    if 'checked_at' in data_dict:
        data_dict['checked_at'] = normalized_dt(data_dict['checked_at'])

    return data_dict
