from datetime import datetime

from django.views.decorators.http import require_GET

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

from staff.whistlah.utils import get_last_activity

from ..permissions.utils import observer_has_perm


@require_GET
@available_for_external
@responding_json
@observer_has_perm('activity')
@use_request_lang
def last_activity(request, login):
    activity = get_last_activity([login])[login]
    if not activity:
        return {}

    activity = localize(activity)
    delta = (datetime.now() - activity['updated_at']).total_seconds()

    return {'target': {'last_activity': {
        'office_name': activity['name'],
        'office_codes': activity['office_parts_codes'],
        'seconds_ago': int(delta),
    }}}
