from django.shortcuts import render,get_object_or_404
from .models import Post
from .forms import PostForm
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required


def post_list(request):
	posts=Post.objects.filter(published_date__isnull=False).order_by('-pk')#'-published_date')
	return render(request,'post_list.html',{'posts':posts})

def post_detail(request,pk):
	post=get_object_or_404(Post,pk=pk)
	return render(request,'post_detail.html',{'post':post})

@login_required
def post_new(request):
	if request.method=='POST':
		form=PostForm(request.POST)
		if form.is_valid():
			post=form.save(commit=False)
			post.author=request.user
			post.save()
			return redirect('blog.views.post_detail',pk=post.pk)
	else:
		form=PostForm()
	return render(request,'post_edit.html',{'form':form})

@login_required
def post_edit(request,pk):
	post=get_object_or_404(Post,pk=pk)
	if request.method=='POST':
		form=PostForm(request.POST,instance=post)
		if form.is_valid():
			post=form.save(commit=False)
			post.author=request.user
			post.save()
			return redirect('blog.views.post_detail',pk=post.pk)
	else:
		form=PostForm(instance=post)
	return render(request,'post_edit.html',{'form':form})

def post_draft_list(request):
	posts=Post.objects.filter(published_date__isnull=True).order_by('-created_date')
	return render(request,'post_draft_list.html',{'posts':posts})

@login_required
def post_publish(request,pk):
	post=get_object_or_404(Post,pk=pk)
	post.publish()
	return redirect('blog.views.post_detail',pk=post.pk)

@login_required
def post_remove(request,pk):
	post=get_object_or_404(Post,pk=pk)
	post.delete()
	return redirect('blog.views.post_list')
def post_next(request,pk):
	pk=pk-1
	post=post=get_object_or_404(Post,pk=pk)
	return render(request,'post_detail.html',{'post':post})

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