from datetime import date, datetime, timedelta
from staff.django_intranet_notifications import Notification

from staff.lib.utils.list import pairs_iterator
from staff.rfid.constants import OWNER, STATE
from staff.rfid.controllers import Badges


def get_context_data(person, badges_list, date_from):
    data = {
        'first_name': person.first_name,
        'last_name': person.last_name,
        'login': person.login,
        'new_badge': badges_list[0],
        'replacing_date': badges_list[0].created_at,
    }
    old_badges = []
    for new_badge, old_badge in pairs_iterator(badges_list):
        if new_badge.created_at > date_from:
            old_badges.append(old_badge)
        else:
            break
    old_badges.reverse()
    data['old_badges'] = old_badges
    return data


def send_badges_mail():
    ctx = {'persons': []}
    date_from = datetime.now() - timedelta(days=1)

    for badge in Badges().filter(created_at__gte=date_from, owner=OWNER.EMPLOYEE, state=STATE.ACTIVE):
        person = badge.person
        badges = list(person.badges.order_by('-created_at'))
        if len(badges) > 1:
            ctx['persons'].append(get_context_data(person, badges, date_from))
    if ctx['persons']:
        RecreatedBadgesNotification(
            target='BADGES_RECREATED',
            context=ctx
        ).send()


class RecreatedBadgesNotification(Notification):
    template = 'ru/mail/badges_replaced_notification.html'

    def get_subj_id(self):
        return 'badges_email_%s' % date.today()
