from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader import render_to_string
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.forms import UserCreationForm
from .decorators import *
from .forms import PostForm, CustomUserCreationForm, ProfileForm, UserForm
from .filters import PostFilter
from .models import *

# Create your views here.

def home(request):
	posts = Post.objects.filter(active=True, featured=True)[0:3]

	context = {'posts':posts}
	return render(request, 'base/index.html', context)

def posts(request):
	posts = Post.objects.filter(active=True)
	myFilter = PostFilter(request.GET, queryset=posts)
	posts = myFilter.qs

	page = request.GET.get('page')
	paginator = Paginator(posts, 5)

	try:
		posts = paginator.page(page)
	except PageNotAnInteger:
		posts = paginator.page(1)
	except EmptyPage:
		posts = paginator.page(paginator.num_pages)

	context = {'posts':posts, 'myFilter':myFilter}
	return render(request, 'base/posts.html', context)

def post(request, slug):
	post = Post.objects.get(slug=slug)

	if request.method == 'POST':
		PostComment.objects.create(
			author=request.user.profile,
			post=post,
			body=request.POST['comment']
			)
		messages.success(request, "Your comment has been posted successfully!")

		return redirect('post', slug=post.slug)


	context = {'post':post}
	return render(request, 'base/post.html', context)

def profile(request):
	return render(request, 'base/profile.html')

#CRUD VIEWS
@admin_only
@login_required(login_url="home")
def createPost(request):
	form = PostForm()

	if request.method == 'POST':
		form = PostForm(request.POST, request.FILES)
		if form.is_valid():
			form.save()
		return redirect('posts')

	context = {'form':form}
	return render(request, 'base/post_form.html', context)


@admin_only
@login_required(login_url="home")
def updatePost(request, slug):
	post = Post.objects.get(slug=slug)
	form = PostForm(instance=post)

	if request.method == 'POST':
		form = PostForm(request.POST, request.FILES, instance=post)
		if form.is_valid():
			form.save()
		return redirect('posts')

	context = {'form':form}
	return render(request, 'base/post_form.html', context)

@admin_only
@login_required(login_url="home")
def deletePost(request, slug):
	post = Post.objects.get(slug=slug)

	if request.method == 'POST':
		post.delete()
		return redirect('posts')
	context = {'item':post}
	return render(request, 'base/delete.html', context)



def sendEmail(request):

	if request.method == 'POST':

		template = render_to_string('base/email_template.html', {
			'name':request.POST['name'],
			'email':request.POST['email'],
			'message':request.POST['message'],
			})

		email = EmailMessage(
			request.POST['subject'],
			template,
			settings.EMAIL_HOST_USER,
			['cotechlevy@gmail.com']
			)

		email.fail_silently=False
		email.send()

	return render(request, 'base/email_sent.html')

def loginPage(request):
	if request.user.is_authenticated:
		return redirect('home')

	if request.method == 'POST':
		email = request.POST.get('email')
		password =request.POST.get('password')

		#Little Hack to work around re-building the usermodel
		try:
			user = User.objects.get(email=email)
			user = authenticate(request, username=user.username, password=password)
		except:
			messages.error(request, 'User with this email does not exists')
			return redirect('login')
			
		if user is not None:
			login(request, user)
			return redirect('home')
		else:
			messages.error(request, 'Email OR password is incorrect')

	context = {}
	return render(request, 'base/login.html', context)

def registerPage(request):
	form = CustomUserCreationForm()
	if request.method == 'POST':
		form = CustomUserCreationForm(request.POST)
		if form.is_valid():
			user = form.save(commit=False)
			user.save()
			messages.success(request, 'Account successfuly created!')

			user = authenticate(request, username=user.username, password=request.POST['password1'])

			if user is not None:
				login(request, user)

			next_url = request.GET.get('next')
			if next_url == '' or next_url == None:
				next_url = 'home'
			return redirect(next_url)
		else:
			messages.error(request, 'An error has occured with registration')
	context = {'form':form}
	return render(request, 'base/register.html', context)

def logoutUser(request):
	logout(request)
	return redirect('home')

@admin_only
@login_required(login_url="home")
def userAccount(request):
	profile = request.user.profile

	context = {'profile':profile}
	return render(request, 'base/account.html', context)

@login_required(login_url="home")
def updateProfile(request):
	user = request.user
	profile = user.profile
	form = ProfileForm(instance=profile)
	if request.method == 'POST':
		user_form = UserForm(request.POST, instance=user)
		if user_form.is_valid():
			user_form.save()

		form = ProfileForm(request.POST, request.FILES, instance=profile)
		if form.is_valid():
			form.save()
			return redirect('account')


	context = {'form':form}
	return render(request, 'base/profile_form.html', context)

def myEducation(request):
	return render(request, 'base/education.html')

def myExperience(request):
	return render(request, 'base/experience.html')

def myAchievements(request):
	return render(request, 'base/achievements.html')

def myAbout(request):
    return render(request, 'base/about.html')

def myContact(request):
    return render(request, 'base/contact.html')

def mySkills(request):
    return render(request, 'base/skills.html')

[((1835, 1867), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (1849, 1867), False, 'from django.contrib.auth.decorators import login_required\n'), ((2151, 2183), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (2165, 2183), False, 'from django.contrib.auth.decorators import login_required\n'), ((2536, 2568), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (2550, 2568), False, 'from django.contrib.auth.decorators import login_required\n'), ((4713, 4745), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (4727, 4745), False, 'from django.contrib.auth.decorators import login_required\n'), ((4892, 4924), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (4906, 4924), False, 'from django.contrib.auth.decorators import login_required\n'), ((836, 879), 'django.shortcuts.render', 'render', (['request', '"""base/index.html"""', 'context'], {}), "(request, 'base/index.html', context)\n", (842, 879), False, 'from django.shortcuts import render, redirect\n'), ((1062, 1081), 'django.core.paginator.Paginator', 'Paginator', (['posts', '(5)'], {}), '(posts, 5)\n', (1071, 1081), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), ((1296, 1339), 'django.shortcuts.render', 'render', (['request', '"""base/posts.html"""', 'context'], {}), "(request, 'base/posts.html', context)\n", (1302, 1339), False, 'from django.shortcuts import render, redirect\n'), ((1698, 1740), 'django.shortcuts.render', 'render', (['request', '"""base/post.html"""', 'context'], {}), "(request, 'base/post.html', context)\n", (1704, 1740), False, 'from django.shortcuts import render, redirect\n'), ((1772, 1808), 'django.shortcuts.render', 'render', (['request', '"""base/profile.html"""'], {}), "(request, 'base/profile.html')\n", (1778, 1808), False, 'from django.shortcuts import render, redirect\n'), ((2088, 2135), 'django.shortcuts.render', 'render', (['request', '"""base/post_form.html"""', 'context'], {}), "(request, 'base/post_form.html', context)\n", (2094, 2135), False, 'from django.shortcuts import render, redirect\n'), ((2474, 2521), 'django.shortcuts.render', 'render', (['request', '"""base/post_form.html"""', 'context'], {}), "(request, 'base/post_form.html', context)\n", (2480, 2521), False, 'from django.shortcuts import render, redirect\n'), ((2743, 2787), 'django.shortcuts.render', 'render', (['request', '"""base/delete.html"""', 'context'], {}), "(request, 'base/delete.html', context)\n", (2749, 2787), False, 'from django.shortcuts import render, redirect\n'), ((3198, 3237), 'django.shortcuts.render', 'render', (['request', '"""base/email_sent.html"""'], {}), "(request, 'base/email_sent.html')\n", (3204, 3237), False, 'from django.shortcuts import render, redirect\n'), ((3886, 3929), 'django.shortcuts.render', 'render', (['request', '"""base/login.html"""', 'context'], {}), "(request, 'base/login.html', context)\n", (3892, 3929), False, 'from django.shortcuts import render, redirect\n'), ((4584, 4630), 'django.shortcuts.render', 'render', (['request', '"""base/register.html"""', 'context'], {}), "(request, 'base/register.html', context)\n", (4590, 4630), False, 'from django.shortcuts import render, redirect\n'), ((4658, 4673), 'django.contrib.auth.logout', 'logout', (['request'], {}), '(request)\n', (4664, 4673), False, 'from django.contrib.auth import logout, login, authenticate\n'), ((4682, 4698), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (4690, 4698), False, 'from django.shortcuts import render, redirect\n'), ((4844, 4889), 'django.shortcuts.render', 'render', (['request', '"""base/account.html"""', 'context'], {}), "(request, 'base/account.html', context)\n", (4850, 4889), False, 'from django.shortcuts import render, redirect\n'), ((5336, 5386), 'django.shortcuts.render', 'render', (['request', '"""base/profile_form.html"""', 'context'], {}), "(request, 'base/profile_form.html', context)\n", (5342, 5386), False, 'from django.shortcuts import render, redirect\n'), ((5422, 5460), 'django.shortcuts.render', 'render', (['request', '"""base/education.html"""'], {}), "(request, 'base/education.html')\n", (5428, 5460), False, 'from django.shortcuts import render, redirect\n'), ((5497, 5536), 'django.shortcuts.render', 'render', (['request', '"""base/experience.html"""'], {}), "(request, 'base/experience.html')\n", (5503, 5536), False, 'from django.shortcuts import render, redirect\n'), ((5575, 5616), 'django.shortcuts.render', 'render', (['request', '"""base/achievements.html"""'], {}), "(request, 'base/achievements.html')\n", (5581, 5616), False, 'from django.shortcuts import render, redirect\n'), ((5651, 5685), 'django.shortcuts.render', 'render', (['request', '"""base/about.html"""'], {}), "(request, 'base/about.html')\n", (5657, 5685), False, 'from django.shortcuts import render, redirect\n'), ((5722, 5758), 'django.shortcuts.render', 'render', (['request', '"""base/contact.html"""'], {}), "(request, 'base/contact.html')\n", (5728, 5758), False, 'from django.shortcuts import render, redirect\n'), ((5794, 5829), 'django.shortcuts.render', 'render', (['request', '"""base/skills.html"""'], {}), "(request, 'base/skills.html')\n", (5800, 5829), False, 'from django.shortcuts import render, redirect\n'), ((1548, 1619), 'django.contrib.messages.success', 'messages.success', (['request', '"""Your comment has been posted successfully!"""'], {}), "(request, 'Your comment has been posted successfully!')\n", (1564, 1619), False, 'from django.contrib import messages\n'), ((1630, 1662), 'django.shortcuts.redirect', 'redirect', (['"""post"""'], {'slug': 'post.slug'}), "('post', slug=post.slug)\n", (1638, 1662), False, 'from django.shortcuts import render, redirect\n'), ((2036, 2053), 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), "('posts')\n", (2044, 2053), False, 'from django.shortcuts import render, redirect\n'), ((2422, 2439), 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), "('posts')\n", (2430, 2439), False, 'from django.shortcuts import render, redirect\n'), ((2692, 2709), 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), "('posts')\n", (2700, 2709), False, 'from django.shortcuts import render, redirect\n'), ((2860, 3008), 'django.template.loader.render_to_string', 'render_to_string', (['"""base/email_template.html"""', "{'name': request.POST['name'], 'email': request.POST['email'], 'message':\n    request.POST['message']}"], {}), "('base/email_template.html', {'name': request.POST['name'],\n    'email': request.POST['email'], 'message': request.POST['message']})\n", (2876, 3008), False, 'from django.template.loader import render_to_string\n'), ((3028, 3132), 'django.core.mail.EmailMessage', 'EmailMessage', (["request.POST['subject']", 'template', 'settings.EMAIL_HOST_USER', "['cotechlevy@gmail.com']"], {}), "(request.POST['subject'], template, settings.EMAIL_HOST_USER, [\n    'cotechlevy@gmail.com'])\n", (3040, 3132), False, 'from django.core.mail import EmailMessage\n'), ((3307, 3323), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (3315, 3323), False, 'from django.shortcuts import render, redirect\n'), ((3506, 3535), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'email': 'email'}), '(email=email)\n', (3522, 3535), False, 'from django.contrib.auth.models import User\n'), ((3546, 3610), 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'user.username', 'password': 'password'}), '(request, username=user.username, password=password)\n', (3558, 3610), False, 'from django.contrib.auth import logout, login, authenticate\n'), ((3746, 3766), 'django.contrib.auth.login', 'login', (['request', 'user'], {}), '(request, user)\n', (3751, 3766), False, 'from django.contrib.auth import logout, login, authenticate\n'), ((3777, 3793), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (3785, 3793), False, 'from django.shortcuts import render, redirect\n'), ((3805, 3862), 'django.contrib.messages.error', 'messages.error', (['request', '"""Email OR password is incorrect"""'], {}), "(request, 'Email OR password is incorrect')\n", (3819, 3862), False, 'from django.contrib import messages\n'), ((4141, 4198), 'django.contrib.messages.success', 'messages.success', (['request', '"""Account successfuly created!"""'], {}), "(request, 'Account successfuly created!')\n", (4157, 4198), False, 'from django.contrib import messages\n'), ((4210, 4296), 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'user.username', 'password': "request.POST['password1']"}), "(request, username=user.username, password=request.POST[\n    'password1'])\n", (4222, 4296), False, 'from django.contrib.auth import logout, login, authenticate\n'), ((4455, 4473), 'django.shortcuts.redirect', 'redirect', (['next_url'], {}), '(next_url)\n', (4463, 4473), False, 'from django.shortcuts import render, redirect\n'), ((4485, 4550), 'django.contrib.messages.error', 'messages.error', (['request', '"""An error has occured with registration"""'], {}), "(request, 'An error has occured with registration')\n", (4499, 4550), False, 'from django.contrib import messages\n'), ((5281, 5300), 'django.shortcuts.redirect', 'redirect', (['"""account"""'], {}), "('account')\n", (5289, 5300), False, 'from django.shortcuts import render, redirect\n'), ((3624, 3687), 'django.contrib.messages.error', 'messages.error', (['request', '"""User with this email does not exists"""'], {}), "(request, 'User with this email does not exists')\n", (3638, 3687), False, 'from django.contrib import messages\n'), ((3698, 3715), 'django.shortcuts.redirect', 'redirect', (['"""login"""'], {}), "('login')\n", (3706, 3715), False, 'from django.shortcuts import render, redirect\n'), ((4321, 4341), 'django.contrib.auth.login', 'login', (['request', 'user'], {}), '(request, user)\n', (4326, 4341), False, 'from django.contrib.auth import logout, login, authenticate\n')]