from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from datetime import datetime
from .models import lab, labComputo
from autenticacion.models import perfil
from universidad.models import carrera, asignatura, area, material, laboratorio
from .forms import FormlabComputoEnv, FormlabComputo


# Create your views here.


def scan(request):
	return render(request, 'scan.html')


def user(request):
	return render(request, 'user.html')



def lcomputo(request, id):
	if request.method == "POST":
		form = FormlabComputo(request.POST)
		if form.is_valid():
			post = form.save(commit=False)
			post.save()
			messages.success(request, f"El registro se ha creado o actualizado correctamente")
			return redirect('laboratorios', id)
		else:
			for field, items in form.errors.items():
				for item in items:
					messages.error(request, '{}: {}'.format(field, item))
	datos = labComputo.objects.filter(id_lab_id=id)
	perfils = perfil.objects.all()
	users = User.objects.all()
	labos = laboratorio.objects.get(id=id)
	asigs = asignatura.objects.all()
	areas = area.objects.all()
	mates = material.objects.all()
	return render(request, 'laboratorios.html', {"datos": datos, "perfils": perfils, "users": users, "labos": labos, "asigs": asigs, "areas": areas, "mates": mates})
	


def LCscan(request, id):
	idlab = id
	return render(request, 'LCscan.html', {"idlab": idlab})


def LCcheckIng(request, id):
	idlab = id
	key = request.POST.get("key")
	datos = perfil.objects.get(key=key)
	user = User.objects.get(id=datos.usuario_id)
	form = FormlabComputoEnv()
	return render(request, 'LCcheckIng.html', {"datos": datos, "form": form, "user": user, "idlab": idlab})


def LCscanS(request, idlab, id):
	idlabx = idlab
	idx = id
	return render(request, 'LCscanS.html', {"idlabx": idlabx, "idx": idx})


def Updatesalida(request, idlab, id ):
	key = request.POST.get("key")
	datosuser = perfil.objects.get(key=key)
	datoslab = labComputo.objects.get(id=id)
	idlabx = idlab
	idx= id
	date = datetime.now()
	if datosuser.usuario_id == datoslab.usuario_id:
		update = labComputo.objects.values('salida').filter(id=idx).update(salida=date)
		return redirect('laboratorios', idlabx)

	return redirect('laboratorios', idlabx)

