from django.contrib.auth.models import User
from django.db.models.signals import pre_save, pre_delete
from django.conf import settings
from django.dispatch import receiver

try:
    from authentic2.custom_user.models import User as A2User
except ImportError:
    pass
except:
    # when user is created or deleted on Docbow, create or delete on authentic
    # when first_name, last_name, email or password change on docbow, write it on authentic

    @receiver(pre_delete, sender=User)
    def user_pre_delete(sender, instance, using, *args, **kwargs):
        '''Delete instances on authentic side'''
        if using != 'default':
            return
        if not 'authentic' in settings.DATABASES:
            return
        username = instance.username
        A2User.objects.using('authentic').filter(username=username).delete()

    @receiver(pre_save, sender=User)
    def user_pre_save(sender, instance, raw, using, *args, **kwargs):
        '''Create new instance on authentic side'''
        if using != 'default':
            return
        if not 'authentic' in settings.DATABASES:
            return
        if instance.id:
            old_instance = User.objects.using(using).get(id=instance.id)
            username = old_instance.username
        else:
            username = instance.username
        try:
            user = A2User.objects.using('authentic').get(username=username)
        except A2User.DoesNotExist:
            update_password = True
            user = A2User()
        user.username = instance.username
        user.first_name = instance.first_name
        user.last_name = instance.last_name
        user.email = instance.email
        user.password = instance.password
        user.save(using='authentic')
