from django.shortcuts import render
from django.template import loader
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages


from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User

#from blog.forms import *
from core.views import gen_page_base, gen_page_sys
from blog.models import *

def blog_index(request, bcat):

	print(bcat)

	template = loader.get_template('listing.html')
	page = gen_page_base()
	page.p_adresse = reverse('blog_index')
	page.p_titre = "Les articles du Blog"
	page.p_contenu = ""
	page.p_right = "Retrouvez les tous les articles de mon blog"

	if bcat == "all":
		page.blog_art = Blog.objects.filter( b_publier = True ).order_by( '-b_publdate' )[:15]
		page.blog_cat = Cat_Blog.objects.all()[:15]
	else :
		page.blog_art = Blog.objects.filter( b_publier = True ).filter( b_cat__cb_titre_slgify = bcat ).order_by( '-b_publdate' )[:15]
		page.blog_cat = Cat_Blog.objects.filter( cb_titre_slgify = bcat )[:15]
		page.retour = "blog_index"

	html = template.render({
		'page': page,
		'user': request.user,
		}, request)
		
	return HttpResponse(html)

def blog_play(request, bart):

	template = loader.get_template('read.html')
	page = gen_page_base()
	page.p_adresse = reverse('blog_index')
	page.blog_art = Blog.objects.filter( b_titre_slugify = bart)[:1]


	for art in page.blog_art:
		page.p_titre = art.b_titre
		page.p_contenu = art.b_description
		page.p_right = art.b_right

	html = template.render({
		'page': page,
		'user': request.user,
		}, request)
		
	return HttpResponse(html)


def blog_update(request):
	arts = Blog.objects.all()
	for art in arts:
		print(art.b_titre_slugify)
		art.b_contenu = art.b_contenu.replace('é"','é').replace('à"','à').replace('ê"','ê').replace('è"','è').replace('ô"', 'ô').replace('«"', '«').replace('»"', '»')
		art.b_contenu = art.b_contenu.replace('rsquo','|||').replace('|||','').replace('"',"'").replace("''","'")
		art.save()
	return HttpResponse("OK")