from django.shortcuts import render, redirect
from .models import Tutorial,TutorialCategory,TutorialSeries
from django.contrib.auth.forms import  AuthenticationForm
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
from .forms import NewUserForm
from django.http import HttpResponse




def homepage(request):
  query = request.GET.get('q')
  if query:
    tutorials  = [t.tutorial_key for t in Tutorial.objects.all()]


    for i in tutorials:
      t = i.split(' ')
      if query in t:
        return render(request,'main/tut.html',{'t':Tutorial.objects.filter(tutorial_key__contains=query)})
    if query not in t:
        messages.info(request, "No tutorials found")
  return render(request=request,
                template_name='main/categories.html',
                context={"categories": TutorialCategory.objects.all})


def register(request):
    if request.method == "POST":
        form = NewUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            c = str({username})
            messages.success(request, "New account created "+username)
            login(request, user)
            return redirect("main:homepage")
        else:
            for msg in form.error_messages:
              c = str({form.error_messages[msg]})
              messages.error(request, c)
              return render(request = request,
                          template_name = "main/Register.html",
                          context={"form":form})

    form = NewUserForm
    return render(request = request,
                  template_name = "main/Register.html",
                  context={"form":form})
def logout_request(request):
  logout(request)
  messages.info(request,'logout successful')
  return redirect('main:homepage')

def login_request(request):
  form = AuthenticationForm()
  return render(request,'main/login.html',{'form':form})



def login_request(request):
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.info(request, "You are now logged in as "+username)
                return redirect('/')
            else:
                messages.error(request, "Invalid username or password.")
        else:
            messages.error(request, "Invalid username or password.")
    form = AuthenticationForm()
    return render(request = request,
                    template_name = "main/login.html",
                    context={"form":form})



...
def single_slug(request, single_slug):
    # first check to see if the url is in categories.
    query = request.GET.get('q')
    if query:
      tutorials  = [t.tutorial_key for t in Tutorial.objects.all()]
      for i in tutorials:
        t = i.split(' ')
        if query in t:
          return render(request,'main/tut.html',{'t':Tutorial.objects.filter(tutorial_key__contains=query)})
      if query not in t:
          messages.info(request, "No tutorials found")

    categories = [c.category_slug for c in TutorialCategory.objects.all()]
    
    if single_slug in categories:
        matching_series = TutorialSeries.objects.filter(tutorial_category__category_slug=single_slug)
        series_urls = {}

        for m in matching_series.all():
            part_one = Tutorial.objects.filter(tutorial_series__tutorial_series=m.tutorial_series).earliest("tutorial_published")
            series_urls[m] = part_one.tutorial_slug

        return render(request=request,
                      template_name='main/category.html',
                      context={"tutorial_series": matching_series, "part_ones": series_urls})

    tutorials  = [t.tutorial_slug for t in Tutorial.objects.all()]
    if single_slug in tutorials:
      return render(request,'main/tut.html',{'t':Tutorial.objects.filter(tutorial_slug=single_slug)})
   

