from django.shortcuts import render, get_object_or_404, redirect

from django.http import HttpResponse
from .models import Contact, EmailMessage
from django.template.loader import get_template
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.core.mail import send_mail
from .forms import FormWithCaptcha
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib import messages

def send_contact_email(email, subject, message):
    subject = "New Contact Request for AI ML Operations, LLC"
    from_email = "ryan@aimloperations.com"
    to="ryan@aimloperations.com"
    d = {"subject": subject, "message": message, "email": email}
    html_content = get_template(r'emails/contact_email.html').render(d)
    text_content = get_template(r'emails/contact_email.txt').render(d)
    
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send(fail_silently=True)

# Create your views here.
def index(request):    
    return render(request, "public/new_index.html", {})

def chat(request):
    return render(request, "public/chat.html", {})

def ai_education(request):
    return render(request, "public/ai_education.html", {})

def computers(request):
    return render(request, "public/computers.html", {})

def web_design(request):
    return render(request, "public/web_design.html", {})

def ai_sensor(request):
    return render(request, "public/ai_sensor.html", {})

def file_hosting(request):
    return render(request, "public/file_hosting.html", {})

def bot(request):
    return render(request, "public/bot.html", {})

def forward_deployed(request):
    return render(request, "public/forward_deployed.html", {})

def ml_model(request):
    return render(request, "public/ml_model.html", {})

def terms_of_service(request):
    return render(request, "public/terms_of_service.html", {})

@login_required
def preview_email(request, pk):
    email_instance = get_object_or_404(EmailMessage, pk=pk)
    context = {
        "title":email_instance.subject,
        "content":email_instance.body
    }
    return render(
        request, 'public/preview_email.html', context
    )

def contact(request):
    errors = ''
    

    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        message = request.POST.get('message', "")
        subject = request.POST.get('subject', "")
        capchaForm = FormWithCaptcha(request.POST)
        
        if len(name) > 0 and len(email) > 0 and len(subject) > 0:
            if settings.DEBUG or capchaForm.is_valid():

            
                # then we are good
                c = Contact(name=name, email=email, blurb=message, subject=subject)
                c.save()
                # send the email.
                try:
                    send_contact_email(email, subject, message)
                except Exception as e:
                    print(f'Error sending the email {e}')
                    print('Contact Request:')
                    print(f'From: {name}')
                    print(f'Message: {message}')
                return render(request, "public/contact.html", {'success':True, 'capchaForm': FormWithCaptcha()})
            else:
                return render(request, "public/contact.html", {'errors': "There was an error submitting. Try again", 'capchaForm': capchaForm})
        else:
            if len(name) == 0 and len(email) == 0:
                errors = 'Both name and email are required'
            elif len(email) == 0:
                errors = 'Email is required'
            elif len(name) == 0:
                errors = 'Name is required'
            # we need to show an error
            return render(request, "public/contact.html", {'errors': errors, 'capchaForm': capchaForm})
    
    capcha = None if settings.DEBUG else FormWithCaptcha()
    return render(request, "public/contact.html", {'capchaForm': capcha})

@login_required
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('public_index')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'public/change_password.html', {
        'form': form
    })
    
