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')

[(65, 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), False, 'from django.contrib.auth.decorators import login_required\n'), (80, 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), False, 'from django.contrib.auth.decorators import login_required\n'), (95, 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), False, 'from django.contrib.auth.decorators import login_required\n'), (182, 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), False, 'from django.contrib.auth.decorators import login_required\n'), (189, 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), False, 'from django.contrib.auth.decorators import login_required\n'), (23, 'django.shortcuts.render', 'render', (['request', '"""base/index.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (31, 'django.core.paginator.Paginator', 'Paginator', (['posts', '(5)'], {}), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), (41, 'django.shortcuts.render', 'render', (['request', '"""base/posts.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (58, 'django.shortcuts.render', 'render', (['request', '"""base/post.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (61, 'django.shortcuts.render', 'render', (['request', '"""base/profile.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (76, 'django.shortcuts.render', 'render', (['request', '"""base/post_form.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (92, 'django.shortcuts.render', 'render', (['request', '"""base/post_form.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (103, 'django.shortcuts.render', 'render', (['request', '"""base/delete.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (127, 'django.shortcuts.render', 'render', (['request', '"""base/email_sent.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (152, 'django.shortcuts.render', 'render', (['request', '"""base/login.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (175, 'django.shortcuts.render', 'render', (['request', '"""base/register.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (178, 'django.contrib.auth.logout', 'logout', (['request'], {}), False, 'from django.contrib.auth import logout, login, authenticate\n'), (179, 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (187, 'django.shortcuts.render', 'render', (['request', '"""base/account.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (206, 'django.shortcuts.render', 'render', (['request', '"""base/profile_form.html"""', 'context'], {}), False, 'from django.shortcuts import render, redirect\n'), (209, 'django.shortcuts.render', 'render', (['request', '"""base/education.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (212, 'django.shortcuts.render', 'render', (['request', '"""base/experience.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (215, 'django.shortcuts.render', 'render', (['request', '"""base/achievements.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (218, 'django.shortcuts.render', 'render', (['request', '"""base/about.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (221, 'django.shortcuts.render', 'render', (['request', '"""base/contact.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (224, 'django.shortcuts.render', 'render', (['request', '"""base/skills.html"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (52, 'django.contrib.messages.success', 'messages.success', (['request', '"""Your comment has been posted successfully!"""'], {}), False, 'from django.contrib import messages\n'), (54, 'django.shortcuts.redirect', 'redirect', (['"""post"""'], {'slug': 'post.slug'}), False, 'from django.shortcuts import render, redirect\n'), (73, 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (89, 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (101, 'django.shortcuts.redirect', 'redirect', (['"""posts"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (111, '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']}"], {}), False, 'from django.template.loader import render_to_string\n'), (117, 'django.core.mail.EmailMessage', 'EmailMessage', (["request.POST['subject']", 'template', 'settings.EMAIL_HOST_USER', "['cotechlevy@gmail.com']"], {}), False, 'from django.core.mail import EmailMessage\n'), (131, 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (139, 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'email': 'email'}), False, 'from django.contrib.auth.models import User\n'), (140, 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'user.username', 'password': 'password'}), False, 'from django.contrib.auth import logout, login, authenticate\n'), (146, 'django.contrib.auth.login', 'login', (['request', 'user'], {}), False, 'from django.contrib.auth import logout, login, authenticate\n'), (147, 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (149, 'django.contrib.messages.error', 'messages.error', (['request', '"""Email OR password is incorrect"""'], {}), False, 'from django.contrib import messages\n'), (161, 'django.contrib.messages.success', 'messages.success', (['request', '"""Account successfuly created!"""'], {}), False, 'from django.contrib import messages\n'), (163, 'django.contrib.auth.authenticate', 'authenticate', (['request'], {'username': 'user.username', 'password': "request.POST['password1']"}), False, 'from django.contrib.auth import logout, login, authenticate\n'), (171, 'django.shortcuts.redirect', 'redirect', (['next_url'], {}), False, 'from django.shortcuts import render, redirect\n'), (173, 'django.contrib.messages.error', 'messages.error', (['request', '"""An error has occured with registration"""'], {}), False, 'from django.contrib import messages\n'), (202, 'django.shortcuts.redirect', 'redirect', (['"""account"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (142, 'django.contrib.messages.error', 'messages.error', (['request', '"""User with this email does not exists"""'], {}), False, 'from django.contrib import messages\n'), (143, 'django.shortcuts.redirect', 'redirect', (['"""login"""'], {}), False, 'from django.shortcuts import render, redirect\n'), (166, 'django.contrib.auth.login', 'login', (['request', 'user'], {}), False, 'from django.contrib.auth import logout, login, authenticate\n')]