# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render


# Create your views here.

from catalog.models import Publisher, News
from django.core.exceptions import ObjectDoesNotExist 
from django.shortcuts import redirect
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json
import datetime
from django.db.models import Q
from .forms import SearchForm
import urllib
from django.db.models import Count
from django.core.urlresolvers import reverse
import json

from django.db.models.functions import TruncMonth, TruncYear
#-------------------------------------------------------------------------------
def getNewsByRequest(request):
	print "getNewsByRequest\n\n\n"


	form = SearchForm(request.GET)
	myQuery = ~Q()

	if 'publishers' in request.GET and request.GET['publishers']!="None" and request.GET['publishers']!="" and request.GET['publishers']!="[]":
		myQuery &= Q(publisher_id__in=form['publishers'].value())

        if 'startDate' in request.GET and request.GET['startDate']!="None" and request.GET['startDate']!="":
		myQuery &= Q(date__gte=request.GET['startDate'])

        if 'endDate' in request.GET and request.GET['endDate']!="None" and request.GET['endDate']!="":
		myQuery &= Q(date__lte=request.GET['endDate'])

	if "text" in request.GET and request.GET['text']!="None" and request.GET['text']!="":
 		myQuery &= Q(text__icontains=request.GET['text'])
	

	print myQuery

	return News.objects.all().filter(myQuery)

#-------------------------------------------------------------------------------
def index(request):
	"""
	View function for home page of site.
	"""
	news = getNewsByRequest(request)
	form = SearchForm(request.GET.copy())

	if 'startDate' not in form or ('startDate' in form and form['startDate'].value == ""):
		form.data.update({'startDate':news.earliest('date').date.strftime("%Y-%m-%d")})

	if 'endDate' not in form or ('endDate' in form and form['endDate'].value == ""):
		form.data.update({'endDate':news.latest('date').date.strftime("%Y-%m-%d")})

	info = dict()
	info['nPublishers'] = news.values('publisher').distinct().count()
	info['nNews'] = news.count()

	queryset = news.values("publisher").order_by("publisher").annotate(count = Count('publisher') )

	urlDict = dict()
	for q in queryset:
		myRequest = request.GET.copy()
		myRequest.update({"publishers":q['publisher']})
		urlDict[q['publisher']] = urllib.urlencode(myRequest)
	print urlDict
	donutChart = [{"label": Publisher.objects.get(id=q['publisher']).name, "value":q["count"], "url":urlDict[q['publisher']]} for q in queryset]


        publishers = Publisher.objects.all().filter( Q(id__in = news.values('publisher').distinct()))


	queryset = news.values("publisher").annotate(day=TruncMonth('date') )


	dateList =[q['day'].strftime("%Y-%m-%d") for q in queryset.values("day").distinct().order_by("-day")]
	dateDicts = {p.shortName:{ n['day'].strftime("%Y-%m-%d"):n['count'] for n in queryset.filter(publisher=p.id).values("day").distinct().order_by("-day").annotate(count = Count('publisher')) } for p in publishers}

	histogramsData = [ {  "date":d, "data":{ k:(dateDicts[k][d] if d in dateDicts[k] else 0) for k in dateDicts.keys()}  }  for d in dateList] 
	histogramsLabels = [p.shortName for p in publishers]

	return render(request,'index.html',{"form":form, "info":info, "donutChart":donutChart, "histogram": histogramsData, "histogramsLabels":histogramsLabels})
#-------------------------------------------------------------------------------
def publisherList(request, type="all"):
        form = SearchForm(request.GET)

	typeQuery = ~Q()
	if type!="all":
		typeQuery = Q(type=type)

		
	news = getNewsByRequest(request)
	publishers = Publisher.objects.all().filter( Q(id__in = news.values('publisher').distinct()) & typeQuery)


	for p in publishers:
		newsTemp = news.filter(publisher=p).order_by("date")
		p.news = newsTemp.count()
		p.date = 0
		if p.news>0:
			p.date = newsTemp[0].date.date()
		else:
			p.date = "-"

	myRequest=request.GET.copy()
	if 'publishers' in myRequest:
		del myRequest['publishers']

        return render(request,'publisherList.html',{"form":form, "publishers":publishers, "queryurl":urllib.urlencode(myRequest)})

#-------------------------------------------------------------------------------
def newsList(request, publisherShortName="all"):
        form = SearchForm(request.GET)

        return render(request,'newsList.html',{"form":form})

#-------------------------------------------------------------------------------
def wsNewsList(request):#, publisherShortName="all"):

	print request.GET
	columns = ['title', 'url', 'date']
	order = dict()
	order["asc"]=""
	order["desc"]="-"
	orderBy = columns[ int(request.GET["order[0][column]"]) ]
	direction = order[request.GET["order[0][dir]"]]

        startDate = datetime.datetime(1950,1,1,0,0,0)
        endDate = datetime.datetime.today()

	request.GET = request.GET.copy()

	if 'ajaxPublishers[]' in request.GET:
		request.GET.setlist('publishers', request.GET.getlist('ajaxPublishers[]'))
		del request.GET['ajaxPublishers[]']

	news = getNewsByRequest(request).order_by(direction+orderBy)

	if 'search[value]' in request.GET and request.GET['search[value]'] != "":
		search = request.GET['search[value]']
		news = news.filter(text__icontains=search)

	data = dict()
	data['data']=list()
	data['recordsTotal'] = news.count()
	data['recordsFiltered'] = news.count()

	paginator = Paginator(news, request.GET['length'])
	page = (int(request.GET['start'])/int(request.GET['length']))+1

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

	for n in news:
		row = list()
		row.append('<a href="'+reverse('news-details', args =(n.id,) )+'">'+ n.title+ '</a>')
                row.append('<a href="'+n.url+'" target="blank">'+n.publisher.shortName+'</a>')
                row.append(n.date.strftime("%Y-%m-%d"))
		data['data'].append(row)

#	print request.GET
	return HttpResponse(json.dumps(data), content_type="application/json")
#-------------------------------------------------------------------------------
def newsDetails(request, newsId):
        form = SearchForm(request.GET)
	news = News.objects.get(id=newsId)
        return render(request,'newsDetails.html',{"form":form,"news":news})

