from django.shortcuts import render,redirect
from .models import Post, ConusFilePDF
from django.contrib.auth.decorators import login_required
from . import forms

# Create your views here.


def post_list(request):
    posts = Post.objects.all().order_by('-date')
    return render(request, 'post/post_list.html', {'posts': posts})

def post_page(request, slug):
    post = Post.objects.get(slug=slug)
    return render(request, 'post/post_page.html', {'post': post})

@login_required(login_url="/users/login/")
def post_new(request):
    if request.method == "POST":
        form = forms.CreatePost(request.POST, request.FILES)
        if form.is_valid():
            newpost = form.save(commit=False)
            newpost.author = request.user
            newpost.save()
            return redirect('post:list')
    else:
        form = forms.CreatePost()
    return render(request, 'post/post_new.html', {'form': form})


def pdf_page(request):
    if request.method == "POST":
        form = forms.UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #Handleuploaded file
            form.save()
            return redirect('post:pdf_page')
    else:
        form = forms.UploadFileForm()
    return render(request, 'post/pdf_page.html', {'form' : form})


def pdf_list(request):
    pdfs = ConusFilePDF.objects.all()
    return render(request, 'post/pdf_list.html', {'pdfs': pdfs})