import datetime

from django.utils import timezone
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 marktplatz.models import *



# This will trigger all products, including wohn- mobi-, erna-, ener-
@receiver(post_save, sender=Product)
def search_agent(sender, instance, update_fields=None, **kwargs):
    # print("signal called")
    if instance.frei == 'JAJA' and instance.public == True :

        # SAVE an object that will trigger the search loop later.
        trigger = Trigger(ort=instance.ort, instancepk = instance.pk  )
        trigger.save()


def process_triggers():

    for trigger in Trigger.objects.filter(sent=False):
        instance = Product.objects.get(pk = trigger.instancepk)

        for agent in SearchAgent.objects.all(  ):

            # This is needed because ort is a multiple selection.
            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']= 'https://' + config.WEBSEITE_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': instance.email },
                        priority='medium',
                    )

        Trigger.objects.filter(pk=trigger.pk).update( sent=True, sentdate = timezone.now()  )
