from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
  
from .models import *
from .forms import *
      
from sicurezza.views import *
from comunicazioni.views import *

def AliasList(request):

  session = getSessionParms(request)
  userauth = session['_userauth_']
  alias2edit = session['_alias2edit_']
  domain2edit = session['_domain2edit_']
  request.session['_from_']="Alias:AliasList"

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

  if not domain2edit:
    domain2edit = utenteautorizzato.domain.id

  dominio = Domini.objects.get(pk=domain2edit)
  aliaslist = Alias.objects.filter(domain=domain2edit).order_by('mailfrom')

  value={}
  value['utenteautorizzato'] = utenteautorizzato
  value['alias'] = None
  value['aliaslist'] = aliaslist
  value['dominio'] = dominio
  value['navbar'] = True

  print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  securitylevel = getSecurityLevel(utenteautorizzato.securitylevel_id)
  securityrow = getSecurityRow(utenteautorizzato.securitylevel_id)
  securitylist =  getSecurityList(securityrow)
  value['securitylist'] = securitylist
  value['securityrow'] = securityrow
  value['securityrowLen'] = len(securityrow)

  if request.method=="POST":

    if "Nuovo alias" in request.POST:
      print('nuovo alias')
      request.session['_alias2edit_'] = 0

      #return  HttpResponseRedirect(reverse('Alias:AliasNew',args={}))
      return HttpResponseRedirect(reverse('Alias:AliasEdit',args=[]))

    if "edit" in request.POST:
      print('id da editare',request.POST['edit'])
      request.session['_alias2edit_'] = request.POST['edit']
      
      return HttpResponseRedirect(reverse('Alias:AliasEdit',args={}))

    if "enabledisablebutton" in request.POST :
      print('id da disattivare/attivare',request.POST['enabledisablebutton'])
      idpost = request.POST['enabledisablebutton']
      u = Alias.objects.get(pk=idpost)
      
      u.enabled = not u.enabled
      if not u.locked: u.save()

    if 'deletebutton' in request.POST:
      print('id da disattivare',request.POST['deletebutton'])
      idpost = request.POST['deletebutton']
      u = Alias.objects.get(pk=idpost)
      if not u.locked and not u.enabled:
        u.tobedeleted = not u.tobedeleted
        if u.locked: u.save()

  return render(request,"Alias.List.html",value)

def AliasEdit(request):

  session = getSessionParms(request)
  userauth = session['_userauth_']
  alias2edit = session['_alias2edit_']
  domain2edit = session['_domain2edit_']

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

  value={}
  value['utenteautorizzato'] = utenteautorizzato
  value['navbar'] = True
  print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  securitylevel = getSecurityLevel(utenteautorizzato.securitylevel_id)
  securityrow = getSecurityRow(utenteautorizzato.securitylevel_id)
  securitylist =  getSecurityList(securityrow)
  value['securitylist'] = securitylist
  value['securityrow'] = securityrow
  value['securityrowLen'] = len(securityrow)

  domain = utenteautorizzato.domain
  try:
    domain = Domini.objects.get(pk=domain2edit)
  except domain.DoesNotExist as dne:
    print(dne)

  alias = Alias()
  alias.domain = domain
  alias.enabled = True
  alias.locked = False
  alias.tobedeleted = False

  try:
    alias = Alias.objects.get(pk=alias2edit)
  except Alias.DoesNotExist as dne:
    print(dne)

  print("Alias:",alias.id)
  value['alias'] = alias

  # non effettua il salvataggio, ma ritorna alla lista FTP
  if 'Ritorno' in request.POST:
    return HttpResponseRedirect(reverse('Alias:AliasList'))

  if request.method == 'POST':
    formalias = formAlias(request.POST)
    formalias.update()

    if formalias.is_valid():
      print("alias da salvare:",alias.id)
      print("dominio",formalias.cleaned_data.get('domain'))

      if not alias.locked: alias.mailfrom = formalias.cleaned_data.get('mailfrom').lower()
      if not alias.locked: alias.domain_id = domain.id
      if not alias.locked: alias.mailto = formalias.cleaned_data.get('mailto').lower()
      print("record.mailto:",alias.mailto)

      alias.nota = formalias.cleaned_data.get('nota')
      alias.locked = formalias.cleaned_data.get('locked')
      if not alias.locked: alias.tobedeleted = formalias.cleaned_data.get('tobedeleted')
      if not alias.locked: alias.enabled = formalias.cleaned_data.get('enabled')

      if alias.tobedeleted: alias.enabled=False

      alias.save()

      mailtest = alias.mailfrom + '@' + alias.domain.nome
      sm = ServizioMail()
      sm.set_rcptto(mailtest.strip())
      template=Template.objects.get(pk=getConfigurazione("alias:info"))
      sm.set_oggetto(template.oggetto)
      sm.set_soggetto(template.soggetto)
      dictdict={}
      dictdict['alias'] = alias
      sm.set_data(dictdict)
      sm.send()

      print("record alias:",alias.id)
      request.session['_alias2edit_'] = alias.id

      return HttpResponseRedirect(reverse('Alias:AliasListList'))
    else:
      print('notvalid')
  else:
   ## verifica se e' post o meno....
    print('non e\' post')
    value_account = {}
    value_account['mailfrom'] = alias.mailfrom
    value_account['domain'] = alias.domain_id
    value_account['mailto'] = alias.mailto
    value_account['enabled'] = alias.enabled
    value_account['tobedeleted'] = alias.tobedeleted
    value_account['locked'] = alias.locked
    value_account['nota'] = alias.nota 
    value_account['utenteautorizzato'] = ''.join((utenteautorizzato.mail,'@',utenteautorizzato.domain.nome))
    print('value_account',value_account)

    formalias = formAlias(value_account)
    formalias.update()
    value['formalias'] = formalias
  
  ## check non passato
  print("formalias.errors",formalias.errors)
  for e in formalias.errors:
    print("errors:",e)
  
  return render(request,'Alias.Edit.html',value)

