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

from .models import *
from .forms import *

from supporto import managepassword
from sicurezza.views import *
from logger.views import *
from comunicazioni.views import *
from datetime import date
from configurazione.views import *
from mqtt import views as m
from random import randint

@securitywrap
def FtpList(request):

  session = getSessionParms(request)
  userauth = session['_userauth_']
  ftp2edit = session['_ftp2edit_']
  domain2edit = session['_domain2edit_']

  request.session['_from_']="Ftp:FtpList"
  _from_ = session['_from_']
  print("_from_",_from_)
  print("next",next)

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


  c = m.start()
  m.publish(c,'Messaggio/Ftp',json.dumps({'me':"Accesso al ftp di {}".format(utenteautorizzato.nome)}))

  if not domain2edit:
    domain2edit = utenteautorizzato.domain.id

  dominio = Domini.objects.get(pk=domain2edit)
  ftplist = FTPUser.objects.filter(dominio=domain2edit).order_by('utente')

  value={}
  value['utenteautorizzato'] = utenteautorizzato
  value['ftp'] = None
  value['ftplist'] = ftplist
  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)
  value['CANWRITE']=True #per il momento, questo flag serve a capire se e' un record nuovo

  if request.method=="POST":

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

    if "Nuovo Accesso FTP" in request.POST:
      print('nuovo ftp')
      request.session['_ftp2edit_'] = 0
      return  HttpResponseRedirect(reverse('Ftp:FtpEdit',args={}))

    if "BackupAllFTPHTTP" in request.POST:
      for d in value['ftplist']:
        q={}
        q['op']='backup'
        q['do']=d.dominio.nome
        q['dt']=d.dominio.http_server.path
        q['ho']=d.ftpgroup.directory % {'site':d.dominio.nome,'ftp':d.utente}
        if d.ftpgroup.section == 'http':
          q['su']='site'
        else:
          q['su'] = ''
        topic = 'ftp/' + d.dominio.http_server.nome.strip()
        print('topic:',topic,q)
        m.publish(c,topic,json.dumps(q))
        topic = '/Richiesta/Ftp/' + d.dominio.http_server.nome.strip()
        print('topic:',topic,q)
        m.publish(c,topic,json.dumps(q))

        '''
      record.dominio__id = formftp.cleaned_data.get('dominio')
      record.utente = formftp.cleaned_data.get('utente')
      record.clear = formftp.cleaned_data.get('password1')
      record.crypt = managepassword.GeneraPassword(record.clear)
      record.password_change_enabled = formftp.cleaned_data.get('password_change_enable')
      record.enabled = formftp.cleaned_data.get('enabled')
      record.tobedeleted = formftp.cleaned_data.get('tobedeleted')
      record.ftpgroup_id = formftp.cleaned_data.get('ftpgroup')
      record.ftpserver_id = formftp.cleaned_data.get('ftpserver')
         '''

    if "Edit" in request.POST:
      print('id da editare',request.POST['Edit'])
      request.session['_ftp2edit_'] = request.POST['Edit']
      return HttpResponseRedirect(reverse('Ftp:FtpEdit',args={}))

    if "enabledisablebutton" in request.POST:
      print('id da gestioree',request.POST['enabledisablebutton'])
      idpost = request.POST['enabledisablebutton']
      u = FTPUser.objects.get(pk=idpost)
      u.enabled= not u.enabled
      t = date.today()
      #u.account_date_disabled=t.strftime("%Y-%m-%d")
      u.save()

    if "BackupFTPHTTP" in request.POST:
      print('id da attivare',request.POST.get('BackupFTPHTTP'))
      idpost = request.POST.get('BackupFTPHTTP')
      u = FTPUser.objects.get(pk=idpost)

      q={}
      q['op']='backup'
      q['do']=u.dominio.nome
      q['dt']=u.dominio.http_server.path
      q['ho']=u.ftpgroup.directory % {'site':u.dominio.nome,'ftp':u.utente}
      if u.ftpgroup.section == 'http':
        q['su']='/site'
      else:
        q['su'] = ''
      topic = 'Ftp/' + u.dominio.http_server.nome.strip()
      print('topic:',topic,q)
      m.publish(c,topic,json.dumps(q))
      topic = '/Richiesta/Ftp/' + u.dominio.http_server.nome.strip()
      print('topic:',topic,q)
      m.publish(c,topic,json.dumps(q))

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

def FtpEdit(request):
  session = getSessionParms(request)
  userauth = session['_userauth_']
  ftp2edit = session['_ftp2edit_']
  domain2edit = session['_domain2edit_']

  _from_ = session['_from_']
  print("_from_",_from_)

  utenteautorizzato = User.objects.get(pk=userauth)
  print('utente autorizzato: ',utenteautorizzato.mail)

  try:
    dominio = Domini.objects.get(pk=domain2edit)
  except Domain.DoesNotExist as dne:
    print("errore, il dominio non e' correttamente gestito in ftpEdit")
    dominio = utenteautorizzato.domain

  if ftp2edit:
    record = FTPUser.objects.get(pk=ftp2edit)
    #aggiorna il record con il contenuto nuovo dei record relativi alla posizione e al server
    tmphomedir = record.ftpgroup.home
    if record.ftpgroup.l3:
      tmphomedir += record.utente + '.'
    tmphomedir += record.dominio.nome
    if len(record.ftpgroup.sub) > 0:
      tmphomedir += record.ftpgroup.sub + record.utente
    print('tmphomedir',tmphomedir)
    record.homedir = tmphomedir
  else:
    record = FTPUser()
    record.utente = str(randint(10000000,99999999))
    record.dominio = dominio
    record.enabled = dominio.enabled
    record.password_change_enabled = True
    record.edit = True #prima volta, si puo' modificare il campo.

  value={}
  value['utenteautorizzato'] = utenteautorizzato
  value['dominio'] = dominio
  value['registrar'] = Registrar.objects.all().filter(enabled=True)
  value['ftp_password_length'] = getConfigurazione('ftp_password_length')
  value['ftp_password_message'] = getConfigurazione('ftp_password_message')
  print(value)

  print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  securitylevel = getSecurityLevel(utenteautorizzato.securitylevel.id)
  securityrow = getSecurityRow(securitylevel.id)
  securitylist = getSecurityList(securityrow)
  value['securityrow'] = securityrow
  value['securityrowLen'] = len(securityrow)
  value['securitylist'] = securitylist
  value['navbar']=True
  value['ftp'] = record
  
  ftpgroup = FTPGroup.objects.filter(enabled=1).order_by('nomegruppo')
  ftpserver = FTPServer.objects.filter(enabled=1).order_by('nome')
  value['ftpgroupv'] = ftpgroup
  value['ftpserverv'] = ftpserver

  if 'Ritorno' in request.POST:
    return HttpResponseRedirect(reverse('Ftp:FtpList'))

  if request.method == "POST":
    ## e' stato richiesto il post.
    formftp = formFtp(request.POST)
    formftp.update()

    if formftp.is_valid():
      print('record valido, via al salvataggio: ',formftp.is_valid())
      record.dominio__id = formftp.cleaned_data.get('dominio')
      record.utente = formftp.cleaned_data.get('utente')
      record.password_change_enabled = formftp.cleaned_data.get('password_change_enabled')
      if record.password_change_enabled:
        record.clear = formftp.cleaned_data.get('password1')
        record.crypt = managepassword.GeneraPassword(record.clear)
      print('password_change_enabled',record.password_change_enabled)
      if 'enabled' in formftp.cleaned_data:
        record.enabled = formftp.cleaned_data.get('enabled')
      print('enabled',formftp.cleaned_data.get('tobedeleted'))
      record.tobedeleted = formftp.cleaned_data.get('tobedeleted')
      record.ftpgroup_id = formftp.cleaned_data.get('ftpgroup')
      record.ftpserver_id = formftp.cleaned_data.get('ftpserver')
      record.mail = formftp.cleaned_data.get('mail')
      record.edit = formftp.cleaned_data.get('edit')
      record.save()

      c = m.start()

      topic = '/Messaggio/Ftp/{}/{}'.format(record.ftpgroup.home,record.dominio.nome)
      m.publish(c,topic,json.dumps({'ftp':'Accesso al ftp di {}@{}'.format(record.utente,record.dominio.nome)}))

      q = {}
      q['op'] = 'CreateSpace'
      q['do'] = record.dominio.nome
      q['dp'] = record.ftpgroup.home
      parametri = {}
      parametri['_defaultdomain_']=record.dominio.nome
      parametri['_defaulthome_']=record.ftpgroup.home
      parametri['_defaultip_']=record.ftpgroup.server
      parametri['_defaulthttpport_'] = record.ftpgroup.http_port
      q['pc'] = getConfigurazione('default_proxy_http_config').format(**parametri)
      q['pf'] = getConfigurazione('default_proxy_http_name').format(**parametri)
      q['wc'] = getConfigurazione('default_webserver_http_config').format(**parametri)
      q['wf'] = getConfigurazione('default_webserver_http_name').format(**parametri)
      print(q)

      m.publish(c,'Http',json.dumps(q))
      m.publish(c,'Richiesta/Http',json.dumps(q))

      # verifica cancellazione
      if record.tobedeleted:
        record.enabled = False
        record.save()

      sm = ServizioMail()
      sql_notifica = getConfigurazione('ftp:notifica')
      sql_notifica = re.split(',| ',sql_notifica)
      sm.set_listadestinatari(sql_notifica)

      if formftp.cleaned_data.get('mail_send'):
        mailweb = formftp.cleaned_data.get('mail')
        mailweb = re.split(',| ',mailweb)
        sm.add_listadestinatari(mailweb)

      # questo dovrebbe essere il profilo per la gestione via mail.
      #sm.add_listadestinatari(getConfigurazione('service'))

      #recuperiamo il template
      template = Template.objects.get(pk=getConfigurazione('ftp:template'))
      template_soggetto = template.soggetto
      sm.set_soggetto(template_soggetto)
      template_oggetto = template.oggetto
      sm.set_oggetto(template_oggetto)

      template_dati = {}
      template_dati['ftpuser'] = record
      sm.set_data(template_dati)

      sm.send()
      return HttpResponseRedirect(reverse('Ftp:FtpList',args={}))

    else:
      print("is_valid: ",formftp.is_valid())
      print("formftp.errors")
      print(formftp.errors)
      for e in formftp.errors:
        print("errors:",e)
      print("***")

    value['formftp'] = formFtp(request.POST)
    value['formftp'].update()
  else:
    ## verifica se e' post o meno....
    print('Post Non validato')
    temp={}
    temp['dominio'] = record.dominio.id
    temp['dominio_domain'] = record.dominio.nome
    temp['utente'] = record.utente

    if ftp2edit:
      print("ftp2edit presente")
      temp['ftpgroup'] = record.ftpgroup_id
      temp['ftpserver'] = record.ftpserver_id
      temp['home'] = record.ftpgroup.home
      temp['sub'] = record.ftpgroup.sub
      temp['l3'] = record.ftpgroup.l3
      temp['edit'] = record.edit

      '''
      21.01.22
      home dir visualizza la path costruita attraverso la query sql
      sqlnamedquery user_by_name SELECT "concat(ftp_user.user,'@',domini.nome) as username,crypt as passwd,ftp_home.uid as uid,ftp_home.gid as gid,concat(ftp_home.home,if(l3,concat(ftp_user.user,'.'),''),domini.nome,if(ftp_home.sub != '',concat(ftp_home.sub,ftp_user.user),'')) as homedir,shell from ftp_user join domini on ftp_user.domain = domini.id join ftp_home on ftp_user.ftp_home = ftp_home.id where (ftp_user.user=substring_index('%U','@',1) and domini.nome=substring_index('%U','@',-1)) and ftp_user.enabled = 1 and ftp_user.tobedeleted = 0 and domini.enabled = 1 and domini.ftp = 1 and domini.tobedeleted = 0 and (ftp_user.server = '7109' or ftp_user.server= '0');"

      if record.l3 la stringa inizia col nome utente che e' il 3 livello
      poi viene il nome dominio
      poi vengono la path ftp e infine l'eventuale utente ftp nel caso sia un ftp non primario (web)
      '''

      tmphomedir = temp['home']
      if temp['l3']:
        tmphomedir += temp['utente'] + '.'
      tmphomedir +=  temp['dominio_domain']
      if len(temp['sub']) > 0:
        tmphomedir += temp['sub'] + temp['utente']
      print('tmphomedir',tmphomedir)
      temp['homedir'] = tmphomedir

      temp['password1'] = record.clear
      temp['password2'] = record.clear

      temp['clear'] = record.clear
    else:
      print("ftp2edit non presente")
      temp['ftpserver'] = 0
      temp['ftpgroup'] = 0

      newpassword = getPassword()
      temp['password1'] = newpassword
      temp['password2'] = newpassword
      temp['clear'] = newpassword

    temp['enabled'] = record.enabled
    temp['tobedeleted'] = record.tobedeleted
    temp['password_change_enabled'] = record.password_change_enabled
    print('password_change_enabled',record.password_change_enabled)

    temp['nota'] = record.nota

    temp['mail'] = record.mail

    temp['edit'] = record.edit

    value['formftp'] = formFtp(temp)
    value['formftp'].update()

  return render(request,"Ftp.Edit.html",value)
