from datetime import datetime
from staff.person.models import Staff
from staff.map.models import Office, City

from staff.lib.decorators import available_by_center_token

from staff.whistlah.models import StaffLastOffice
from . import ApiView


_def_fields = (
    'staff__login',
    'updated_at',
    'is_vpn',
    'office__code',
    'office__name',
    'office__city__name',
)
_full_fields = ApiView.full_fields(StaffLastOffice, {
    'staff': Staff,
    'office': Office,
    'office__city': City,
})


@available_by_center_token
class UserWhereView(ApiView):

    entities = ('users', 'user')

    def prepare_data(self, users, *args, **kwargs):
        now = datetime.now()
        fields = self.get_fields(
            StaffLastOffice, 'fields', _def_fields, _full_fields
        )
        filter = {
            'staff__login__in': [
                x.strip() for x in users.split('|') if x.strip()
            ],
        }
        self.data = list(StaffLastOffice.objects.values(*fields).filter(**filter))
        if 'updated_at' in fields:
            for w in self.data:
                td = now - w['updated_at']
                w['days_ago'] = td.days
                w['hours_ago'] = td.seconds // 3600
                w['minutes_ago'] = (td.seconds - w['hours_ago'] * 3600) // 60
