from django import forms

import re
from sicurezza.views import getSecurityLevelAll
from configurazione.views import *

from .models import *

class formMsg(forms.Form):
  oggetto = forms.CharField(required=True)
  soggetto = forms.CharField(required=True)
  conferma = forms.CharField(required=False)

class formEmail(forms.Form):
  def __init__(self,*args,**kwargs):
    forms.Form.__init__(self,*args,**kwargs)

  def update(self):
    self.fields['mail'] = forms.CharField(required=True)
    self.fields['dominio'] = forms.IntegerField(required=True)
    self.fields['dominio_domain'] = forms.CharField(required=True)

    self.fields['nome'] = forms.CharField(max_length=128,required=True)
    self.fields['nota'] = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':60}),required=False,initial='')

    self.fields['password1'] = forms.CharField(required=True,widget=forms.PasswordInput)
    self.fields['password2'] = forms.CharField(required=True,widget=forms.PasswordInput)
    self.fields['clear'] = forms.CharField(required=False)
    
    self.fields['passwordchanged'] = forms.BooleanField(required=False,widget=forms.HiddenInput) #utilizzato come campo hidden, per segnalare che la password e' stata cambiata.
    self.fields['rigenerapassword'] = forms.BooleanField(required=False,initial=False)
    self.fields['inviaparametri'] = forms.BooleanField(required=False,initial=False)
    self.fields['password_change_enabled'] = forms.BooleanField(required=False,initial=True)
    self.fields['emailtest'] = forms.BooleanField(required=False,initial=False)

    self.fields['pop3'] = forms.BooleanField(required=False,initial=True)
    self.fields['imap'] = forms.BooleanField(required=False,initial=True)
    self.fields['smtp'] = forms.BooleanField(required=False,initial=True)
    self.fields['smtp_relay'] = forms.BooleanField(required=False,initial=True)
    self.fields['lmtp'] = forms.BooleanField(required=False,initial=True)

    self.fields['lmtp_server'] = forms.IntegerField(required=False,initial=0)
    self.fields['mail_server'] = forms.IntegerField(required=False,initial=0)
    self.fields['sql_remote'] = forms.IntegerField(required=False,initial=0)
    self.fields['mail_proxy'] = forms.IntegerField(required=False,initial=0)

    self.fields['webmail'] = forms.BooleanField(required=False,initial=True)
    self.fields['sms'] = forms.BooleanField(required=False,initial=False)
    self.fields['securitylevel'] = forms.ChoiceField(required=False,choices=self.getLevel())
    self.fields['nextcloud'] = forms.BooleanField(required=False,initial=False)
    self.fields['nextcloud_pwd'] = forms.BooleanField(required=False,initial=True)
    self.fields['tobedeleted'] = forms.BooleanField(required=False,initial=False)
    self.fields['enabled'] = forms.BooleanField(required=False,initial=True)
    self.fields['sendafile'] = forms.BooleanField(required=False)
    self.fields['warning_mail_quota']= forms.IntegerField(required=False,initial=0)
    self.fields['limit_mail_quota'] = forms.IntegerField(required=False,initial=0)
    self.fields['mail_di_recupero'] = forms.CharField(required=False,initial="")
    self.fields['mail_who'] = forms.CharField(required=False,initial='')
    self.fields['sieve'] = forms.BooleanField(required=False,initial=1)
    self.fields['antivirus'] = forms.BooleanField(required=False,initial=1)
    self.fields['blacklist'] = forms.BooleanField(required=False,initial=1)
    self.fields['spf'] = forms.BooleanField(required=False,initial=1)
    self.fields['mail_quota'] = forms.IntegerField(required=False,initial=1)
    self.fields['forward'] = forms.CharField(required=False,initial="")

  def clean_password1(self):

    # non e' possibile cambiare la password
    #if not self.data['password_change_enabled']:
    #  print('non e\' possibile cambiare la password')
    #  raise forms.ValidationError("Non si e' abilitati a cambiare la password")

    #bypass in caso di password non modificata
    print('stato password changed:',self.data['passwordchanged'])
    if self.data['passwordchanged'] == '0':
      return self.data['password1']

    # nel caso la mail sia disattivata o da cancellare, bypass
    if 'enabled' in self.data and self.data['enabled'] == 1 and 'tobedeleted' in self.data and self.data['tobedeleted'] == 0:
      return self.data['password1']

    # password uguali nei due campi
    print(self.data['password1'])
    print(self.data['password2'])

    if self.data['password1'] != self.data['password2']:
      raise forms.ValidationError("I due campi password devono essere uguali")

    # lunghezza password
    if len(self.data['password1'].strip()) < int(getConfigurazione('mail_password_length')):
      raise forms.ValidationError("Password troppo corta!")

    # stessa password usata attualmente
    if 'mail' in self.data:
      if self.data['password1'].strip() == self.data['mail']:
        raise forms.ValidationError("Password gia' utilizzata")

    # password = nome 
    if self.data['password1'].strip() == self.data['nome']:
      raise forms.ValidationError("Password uguale al nome")

    # presenza di spazi non validi
    if re.search('\s',self.data['password1']):
      raise forms.ValidationError("Sono presenti caratteri non validi. I caratteri accettati sono: a-z,A-Z,0-9 e \.\,\[\!\@\#\$\%\^\&\*\?\_\~\-\:\;\(\)\[\]\{\}")

    if re.search('\d',self.data['password1']):
      if re.search('[a-z]',self.data['password1']):
        if re.search('[A-Z]',self.data['password1']):
          if re.search('[\.\,\[\!\@\#\$\%\^\&\*\?\_\~\-\:\;\(\)\[\]\{\}]',self.data['password1']):
            return self.data['password1']
  
    raise forms.ValidationError("Non e' presente almeno un numero, una lettera maiuscola, una minuscola e un simbolo")
    
    #return self.data['password1']

  #def clean_password2(self):
  #  if self.fields['password1'] != self.fields['password2']:
  #    raise forms.ValidationError('Confronto Email non riuscito')
  #  return self.fields['password2']

  def clean__mail(self):
    if ('@',' ','!') in self.data['mail']: 
      raise forms.ValidationError('Caratteri non validi')
    return self.data['mail']

  def getLevel(self):
    securitylevel = []
    s = getSecurityLevelAll()
    #s = SecurityLevel.objects.filter(enabled=True).order_by('nome')
    for i in s:
      securitylevel.append((i.id,i.nome))
    return securitylevel
