from django.dispatch import receiver
from django.urls import reverse
from django.forms.models import model_to_dict
from django.db.models.signals import post_delete, post_save

from constance import config
from post_office import mail
from django.core.mail import EmailMessage
from django.core.mail import EmailMultiAlternatives

from .models import *



@receiver(post_save, sender=Product)
@receiver(post_save, sender=Wohnprojekt)
def search_agent(sender, instance, update_fields=None, **kwargs):
    # print("signal called")
    if update_fields is not None:
        if 'frei' in update_fields:
            if instance.frei == 'JAJA' :
                for agent in SearchAgent.objects.all():
                    for agentOrt in agent.ort:
                        if agentOrt == instance.ort:

                            context = {}
                            context['product'] = model_to_dict ( instance )
                            context['agent']   = model_to_dict ( agent )

                            context['product']['status']  =  instance.get_status_display()
                            context['product']['ort']     =  instance.get_ort_display()
                            context['agent']['delete_url']= instance.current_uri + reverse(  'search-agent-delete' , kwargs={ 'pk': agent.pk, 'hash': agent.hash }   )

                            context['recipient'] = [ agent.email, ]
                            context['msg_subject' ] = ('Gemeinschaffen - ' + instance.name )

                            mail.send(
                                context['recipient'],
                                config.EMAIL_NOREPLY,
                                context = context,
                                template='generic',
                                headers={  'Reply-To': agent.email },
                                priority='now',
                            )
