from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db.models.signals import post_save as db_post_save, m2m_changed
from django.contrib.auth import models as auth_models
from django.utils.translation import ugettext_noop as N_
import django_journal

import models
import middleware


def logged_in_handler(sender, request, user, **kwargs):
    extra = middleware.get_extra()
    kwargs = {}
    msg = '{user} logged in'
    if hasattr(user, 'delegate'):
        kwargs['delegate'] = user.delegate
        msg = '{delegate} logged in'
    if hasattr(user, 'user'):
        user = user.user
    django_journal.record('login', msg, user=user, ip=extra['ip'], **kwargs)


def logged_out_handler(sender, request, user, **kwargs):
    extra = middleware.get_extra()
    msg = '{user} logged out'
    if hasattr(user, 'delegate'):
        kwargs['delegate'] = user.delegate
        msg = '{delegate} logged out'
    if hasattr(user, 'user'):
        user = user.user
    django_journal.record('logout', msg, user=user, ip=extra['ip'], **kwargs)


def modified_data(sender, instance, created, raw, using, **kwargs):
    extra = middleware.get_extra()
    if hasattr(extra['user'], 'is_anonymous') and extra['user'].is_anonymous():
        extra['user'] = '-'
    if created:
        tag = 'create'
        msg = '{user} created {model} {instance}'
    else:
        tag = 'modify'
        msg = '{user} modified {model} {instance}'
    django_journal.record(tag, msg, user=extra['user'], ip=extra['ip'],
            model=sender._meta.module_name, instance=instance)


def list_m2m_changed_handler(sender, instance, action, reverse, model, pk_set, using, **kwargs):
    if action.startswith('pre'):
        return
    action.replace('_', '-')
    extra = middleware.get_extra()
    users = model.objects.filter(pk__in=pk_set or [])
    if action == 'post_clear':
        msg = N_('cleared mailing list {list}')
        users = [None]
    elif action == 'post_add':
        msg = N_('added user {member} to mailing list {list}')
    elif action == 'post_remove':
        msg = N_('removed user {member} from mailing list {list}')
    for user in users:
        django_journal.record(action, msg, list=instance, member=user,
                ip=extra['ip'], user=extra['user'])


user_logged_in.connect(logged_in_handler)
user_logged_out.connect(logged_out_handler)
db_post_save.connect(modified_data, sender=models.MailingList)
db_post_save.connect(modified_data, sender=auth_models.User)
db_post_save.connect(modified_data, sender=auth_models.Group)
m2m_changed.connect(list_m2m_changed_handler,
        sender=models.MailingList.members.through)
