from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

#from .models import *
#rom .forms import *

#from supporto import managepassword
from sicurezza.views import *
from logger.views import *
from comunicazioni.views import *
from datetime import date,datetime
from configurazione.views import *
from django.db import IntegrityError
from .forms import *
from mqtt.views import mqtt
import re
import json
import email as emailSource

def manageSpam(request):
  session = getSessionParms(request)

  userauth = session['_userauth_']
  spam2edit = session['_spam2edit_']
  request.session['_from_']="Spam:manageSpam"

  try:
    utenteautorizzato = User.objects.get(pk=userauth)
  except User.DoesNotExist as dne:
    return  HttpResponseRedirect(reverse('Login:login',args={}))

  mq = mqtt()
  mq.build('topic','messaggio/spam')
  mq.messaggio("Attivazione funzione registrazione spam/ham")
  mq.stampa(True)
  #mq.build('stampa',True)
  mq.pubblica()
  tmp=None
  mq=None

  value={}
  value['utenteautorizzato'] = utenteautorizzato
  value['navbar'] = True

  print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  securitylevel = getSecurityLevel(utenteautorizzato.securitylevel_id)
  securityrow = getSecurityRow(utenteautorizzato.securitylevel_id)

  value['securityrow'] = securityrow
  value['securityrowLen'] = len(securityrow)

  if request.method=="POST":

    if 'ritorno' in request.POST:
      return HttpResponseRedirect(reverse('Login:welcome',args={}))

    formspam = formSpam(request.POST)

    if formspam.is_valid():

      ttt = formspam.cleaned_data.get('tt')
      mmm = formspam.cleaned_data.get('mm')
      email = formspam.cleaned_data.get('email')

      print('tipo',ttt)
      print('mail',mmm)
      print('notifica',email)

      # a questo punto, inviamo il messaggio mqtt
      mq = mqtt()
      mq.build('topic','spam/{}'.format(ttt))
      mq.richiesta('{}'.format(ttt))
      tmp = {}
      tmp['ttt'] = ttt

      completeEmail = emailSource.message_from_string(mmm)
      completeEmailSubject = completeEmail['subject']
      completeEmailFrom = completeEmail['from']
      inter = mmm.split(sep='\n')
      tmp['mmm'] = "\n".join(inter)
      tmp['from'] = completeEmailFrom
      tmp['subject'] = completeEmailSubject
      print("tmp",tmp)

      mq.build('stampa',True)
      mq.build('clear',True)
      mq.build('data',tmp)

      if email:
        print('comunico richiesta notifica')
        mq.build('notifica',email)

      mq.messaggio('Registrazione messaggio amavis sezione {}'.format(ttt))
      mq.pubblica()
      tmp=None
      mq=None

    value['formspam'] = formspam

  return render(request,'manageSpam.html',value)
