from django.core.exceptions import ValidationError
from django.shortcuts import redirect, render
from django.http import HttpResponse
from lists.models import Item, List
# Create your views here.
'''
def home_page(request):
	return render(request,'home.html')
'''	
def personal_home_page(request):
	'''
	if request.method == 'POST':
		Item.objects.create(text=request.POST['item_text'])
		return redirect('/lists/the-only-list-in-the-world/')
	
	kata = None
	jumlah_item = Item.objects.count()
	if jumlah_item == 0:
		kata = "yey, waktunya berlibur"	
	elif jumlah_item > 0 and jumlah_item < 5:
		kata = "sibuk tapi santai"
	elif jumlah_item >= 5:
		kata = "oh tidak"	
	items = Item.objects.all()
	'''
	kata = "yey, waktunya berlibur"
	return render(request, 'home.html',{'kata':kata})

def view_list(request, list_id):
	list_ = List.objects.get(id=list_id)
	jumlah_item = Item.objects.filter(list = list_.id).count()
	kata = None
	error = None
	#jumlah_item = Item.objects.count()
	if jumlah_item == 0:
		kata = "yey, waktunya berlibur"
	elif jumlah_item > 0 and jumlah_item < 5:
		kata = "sibuk tapi santai"
	elif jumlah_item >= 5:
		kata = "oh tidak"

	if request.method == 'POST':
		try:
			item = Item(text=request.POST['item_text'], list=list_)
			item.full_clean()
			item.save()
			return redirect(list_)
		except:
			error = "You can't have an empty list item"
	return render(request, 'list.html', {'list': list_,'kata':kata, 'error': error})

#def new_list(request):
#	list_ = List.objects.create()
#	Item.objects.create(text=request.POST['item_text'], list=list_)
#	return redirect('/lists/%d/' % (list_.id,))
	
def add_item(request,list_id):
	list_ = List.objects.get(id=list_id)
	Item.objects.create(text=request.POST['item_text'], list=list_)
	return redirect('/lists/%d/' % (list_.id,))
	
def personal(request):
	return render(request,'personal.html')

def new_list(request):
	list_ = List.objects.create()
	item = Item.objects.create(text=request.POST['item_text'], list=list_)
	try:
		item.full_clean()
		item.save()
	except ValidationError:
		list_.delete()
		error = "You can't have an empty list item"
		return render(request, 'home.html', {"error": error})	
	return redirect(list_)
