from datetime import date

from django.core.cache import cache
from django.db.models import Q, F
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views.generic import ListView, DetailView
#from silk.profiling.profiler import silk_profile

from config.models import SideBar
from .models import Post, Tag, Category
from comment.models import Comment



class CommonViewMinxin:
	def get_context_data(self, **kwargs):
		context = super().get_context_data(**kwargs)
		context.update({
			'sidebars': self.get_sidebars(),
		})
		context.update(self.get_navs())
		return context

	def get_sidebars(self):
		return SideBar.objects.filter(status=SideBar.STATUS_SHOW)

	def get_navs(self):
		categories = Category.objects.filter(status=Category.STATUS_NORMAL)
		nav_categories = []
		normal_categories = []
		for cate in categories:
			if cate.is_nav:
				nav_categories.append(cate)
			else:
				normal_categories.append(cate)

		return {
			'navs': nav_categories,
			'categories': normal_categories,
		}

class IndexView(CommonViewMinxin, ListView):
	queryset = Post.latest_posts()
	paginate_by = 5
	context_object_name = 'post_list'
	template_name = 'blog/list.html'



class CategoryView(IndexView):
	def get_context_data(self, **kwargs):
		context = super().get_context_data(**kwargs)
		category_id = self.kwargs.get('category_id')
		category = get_object_or_404(Category, pk=category_id)
		context.update({
			'category': category,
		})
		return context


	def get_queryset(self):
		'''重写queryset，根据分类过滤'''
		queryset = super().get_queryset()
		category_id = self.kwargs.get('category_id')
		return queryset.filter(category_id=category_id)



class TagView(IndexView):
	def get_context_data(self, **kwargs):
		context = super().get_context_data(**kwargs)
		tag_id = self.kwargs.get('tag_id')
		tag = get_object_or_404(Tag, pk=tag_id)
		context.update({
			'tag': tag,
		})
		return context


	def get_queryset(self):
		'''重写queryset，根据标签过滤'''
		queryset = super().get_queryset()
		tag_id = self.kwargs.get('tag_id')
		return queryset.filter(tag__id=tag_id)



class PostDetailView(CommonViewMinxin, DetailView):
	queryset = Post.latest_posts()
	template_name = 'blog/detail.html'
	context_object_name = 'post'
	pk_url_kwarg = 'post_id'


	def get(self, request, *args, **kwargs):
		response = super().get(request, *args, **kwargs)
		self.handle_visited()
		return response

	def handle_visited(self):
		increase_pv = False
		increase_uv = False
		uid = self.request.uid
		pv_key = 'pv:%s:%s' % (uid, self.request.path)
		uv_key = 'uv:%s:%s:%s' % (uid, str(date.today()), self.request.path)
		if not cache.get(pv_key):
			increase_pv = True
			cache.set(pv_key, 1, 1*60)    #1分钟有效

		if not cache.get(uv_key):
			increase_uv = True
			cache.set(uv_key, 1, 24*60*60)

		if increase_pv and increase_uv:
			Post.objects.filter(pk=self.object.id).update(pv=F('pv') + 1,
				uv=F('uv') + 1)
		elif increase_pv:
			Post.objects.filter(pk=self.object.id).update(pv=F('pv') + 1)
		elif increase_pv:
			Post.objects.filter(pk=self.object.id).update(pv=F('uv') + 1)


class SearchView(IndexView):
	def get_context_data(self):
		context = super().get_context_data()
		context.update({
			'keyword': self.request.GET.get('keyword', '')
		})
		return context


	def get_queryset(self):
		queryset = super().get_queryset()
		keyword = self.request.GET.get('keyword')
		if not keyword:
			return queryset
		return queryset.filter(Q(title__icontains=keyword) | Q(desc__icontains
			=keyword))



class AuthorView(IndexView):
	def get_queryset(self):
		queryset = super().get_queryset()
		author_id = self.kwargs.get('owner_id')
		return queryset.filter(owner_id=author_id)

'''
def post_list(request, category_id=None, tag_id=None):
	tag = None
	category = None

	if tag_id:
		post_list, tag = Post.get_by_tag(tag_id)
	elif category_id:
		post_list, category=Post.get_by_category(category_id)
	else:
		post_list = Post.latest_posts()

	context = {
	    'category': category,
	    'tag': tag,
	    'post_list': post_list,
	    'sidebars': SideBar.get_all(),
	}
	context.update(Category.get_navs())
	return render(request, 'blog/list.html', context=context)


def post_detail(request, post_id=None):
	try:
		post = Post.objects.get(id=post_id)
	except Post.DoesNotExist:
		raise Http404('Post does not exist!')

	context={
	    'post': post,
	    'sidebars': SideBar.get_all(),
	}
	context.update(Category.get_navs())
	return render(request, 'blog/detail.html', context=context)
'''


[((26, 9, 26, 59), 'config.models.SideBar.objects.filter', 'SideBar.objects.filter', (), '', False, 'from config.models import SideBar\n'), ((55, 13, 55, 56), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (), '', False, 'from django.shortcuts import get_object_or_404\n'), ((74, 8, 74, 41), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (), '', False, 'from django.shortcuts import get_object_or_404\n'), ((107, 9, 107, 26), 'django.core.cache.cache.get', 'cache.get', ({(107, 19, 107, 25): 'pv_key'}, {}), '(pv_key)', False, 'from django.core.cache import cache\n'), ((109, 3, 109, 29), 'django.core.cache.cache.set', 'cache.set', ({(109, 13, 109, 19): 'pv_key', (109, 21, 109, 22): '(1)', (109, 24, 109, 28): '(1 * 60)'}, {}), '(pv_key, 1, 1 * 60)', False, 'from django.core.cache import cache\n'), ((111, 9, 111, 26), 'django.core.cache.cache.get', 'cache.get', ({(111, 19, 111, 25): 'uv_key'}, {}), '(uv_key)', False, 'from django.core.cache import cache\n'), ((113, 3, 113, 33), 'django.core.cache.cache.set', 'cache.set', ({(113, 13, 113, 19): 'uv_key', (113, 21, 113, 22): '(1)', (113, 24, 113, 32): '(24 * 60 * 60)'}, {}), '(uv_key, 1, 24 * 60 * 60)', False, 'from django.core.cache import cache\n'), ((138, 25, 138, 52), 'django.db.models.Q', 'Q', (), '', False, 'from django.db.models import Q, F\n'), ((138, 55, 139, 12), 'django.db.models.Q', 'Q', (), '', False, 'from django.db.models import Q, F\n'), ((106, 37, 106, 49), 'datetime.date.today', 'date.today', ({}, {}), '()', False, 'from datetime import date\n'), ((116, 52, 116, 59), 'django.db.models.F', 'F', ({(116, 54, 116, 58): '"""pv"""'}, {}), "('pv')", False, 'from django.db.models import Q, F\n'), ((117, 7, 117, 14), 'django.db.models.F', 'F', ({(117, 9, 117, 13): '"""uv"""'}, {}), "('uv')", False, 'from django.db.models import Q, F\n'), ((119, 52, 119, 59), 'django.db.models.F', 'F', ({(119, 54, 119, 58): '"""pv"""'}, {}), "('pv')", False, 'from django.db.models import Q, F\n'), ((121, 52, 121, 59), 'django.db.models.F', 'F', ({(121, 54, 121, 58): '"""uv"""'}, {}), "('uv')", False, 'from django.db.models import Q, F\n')]