from django.shortcuts import render
from django.urls import reverse
from .models import * 
from .forms import *
import hashlib
from django.http import HttpResponseRedirect

#from mqtt.service import *

# Create your views here.
def lista(request):
  t = None

  if 'ordine_id' in request.POST:
    request.session['template:ordine']='id'
  if 'ordine_alfabetico' in request.POST:
    request.session['template:ordine'] = 'alfabetico'

  if 'template:ordine' in request.session:
    if request.session['template:ordine'] == 'id':
      t = Template.objects.all().order_by('id')

    if request.session['template:ordine'] == 'alfabetico':
      t = Template.objects.all().order_by('nome') 
  else:
    request.session['template:ordine'] = 'id'
    t = Template.objects.all().order_by('id')

  data={}
  data['navbar']=1
  data['template']=t

  return render(request,'template.list.html',data)  

def edit(request,id=None):
  print("id:",id)
  if not id:
    return lista(request)

  data = {}
  data['navbar'] = False
  t = Template()
  print("fino a qui....")
  try:
    t = Template.objects.get(pk=id)
  except Template.DoesNotExist as dne:
    print("Arrivato un id estraneo:",id)

  if request.method == 'POST':
    if 'Ritorna' in request.POST:
      return HttpResponseRedirect(reverse('Template:edit',args={}))

    TF = TemplateForm(request.POST)
    if TF.is_valid():
      t.nome = TF.cleaned_data.get('nome')
      t.soggetto = TF.cleaned_data.get('soggetto')
      t.oggetto = TF.cleaned_data.get('oggetto')
      t.enabled = TF.cleaned_data.get('enabled')
      t.html = TF.cleaned_data.get('html')
      t.note = TF.cleaned_data.get('note')
      t.save()

      print("Dati salvati:",t.id)
      return HttpResponseRedirect(reverse("Template:lista",args={}))
    else:
      print('TF non valido')

  tmp = {}
  tmp['nome'] = t.nome
  tmp['soggetto'] =t.soggetto
  tmp['oggetto'] = t.oggetto
  tmp['enabled'] = t.enabled
  tmp['html'] = t.html
  tmp['note'] = t.note
  TF = TemplateForm(tmp)

  data['template'] = TF
  print(data['template'])

  return render(request,"template.edit.html",data)
