from django.shortcuts import render, redirect
from django.urls import reverse
from django.core.mail import EmailMessage
from .models import Project
from .forms import ContactForm


def home(request):
    projects = Project.objects.all()

    # Form
    contact_form = ContactForm()
    if request.method == "POST":
        contact_form = ContactForm(data=request.POST)
        if contact_form.is_valid():
            name = request.POST.get('name', '')
            email = request.POST.get('email', '')
            content = request.POST.get('content', '')
            # Send Email
            msg = EmailMessage(
                "Personal-Site: Nuevo mensaje",
                "De {} <{}>\n\nEscribió:\n\n{}".format(name, email, content),
                "noreply@heckyel.ga",
                ["heckyel@riseup.net"],
                reply_to=[email],
            )
            try:
                msg.send(fail_silently=False)
                # ok
                return redirect(reverse('home')+"?ok")
            except:
                # Fail
                return redirect(reverse('home')+"?fail")
    # EndForm

    return render(request, 'trabajo/index.html',
                  {'projects': projects, 'form': contact_form})
