import logging
import json
import simplejson as json
from django.http import Http404
from django.http import HttpResponse
#from django.http import HttpResponseRedirect
#from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from controller.Searcher import Searcher
from controller.ClusterAnnotation import ClusterAnnotation
from controller.DocumentAnnotation import DocumentAnnotation
from controller.DocumentaryFile import DocumentaryFile
from controller.Documents import Documents 
from controller.DocumentaryFiles import DocumentaryFiles
from controller.Clusters import Clusters
from controller.DocumentaryFileAnnotation import DocumentaryFileAnnotation
from document.models import Documentaryfile


logger = logging.getLogger('document')

def main_page(request):
	print 'main_page called'
	return render_to_response('index.html')

def login_view(request):
	logger.info('login_view called!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
	print request
	username = request.POST['username']
	password = request.POST['password']
	user = authenticate(username=username, password=password)
	my_data_dictionary = {'loginstatus': ''}
	my_data_dictionary['dossierDocs'] = []
	
	if user is not None:
		if user.is_active:
			login(request, user)
			dossierDoc = []
			documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
			if documentaryFiles:
				for docfile in documentaryFiles:
					dossierDoc.append({'title':docfile.title, 'description':docfile.description, 'url':docfile.image.url})
				
				my_data_dictionary['dossierDocs'].append(dossierDoc)
				request.session['dossierDocs'] = dossierDoc
			logger.info(my_data_dictionary['dossierDocs'])
			print 'user logged'
		else:
			logger.info('user not active')
			print 'user not active'
			my_data_dictionary['loginstatus'] = 'Utilisateur inactif'
	else:
		print 'invalid user'
		logger.info('invalid user')
		my_data_dictionary['loginstatus'] = 'Idenfiant ou mot de passe incorrect'
	
	request.session['refreshOnly'] = True
	print 'next!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
	print request.GET.get('next', '/')
	return HttpResponseRedirect(request.GET.get('next', '/')) 


def logout_view(request):
	"""
	Logout users out and re-direct them to the main page.
	"""
	query_id = request.session['query_id']
	key1 = request.session['key1']
	json2 = request.session['json2']
	json = request.session['json']
	
	logout(request)
	request.session['refreshOnly'] = True
	request.session['query_id'] = query_id
	request.session['key1'] = key1
	request.session['json2'] = json2
	request.session['json'] = json
	return HttpResponseRedirect(request.GET.get('next', '/')) 


def document_main_page(request):
	logger.info('document_main_page called')
	request.session['refreshOnly'] = False
	request.session['json2'] = {}
	request.session['json'] = {}
	request.session['query_id'] = ''
	request.session['key1'] = ''
	
	my_data_dictionary = {'user': request.user}
	my_data_dictionary['loginstatus'] = ''
	my_data_dictionary['dossierDocs'] = []
	dossierDoc = []
	
	if not request.user.is_authenticated():
		print 'Anonymous user'
		return render_to_response('index.html', my_data_dictionary, context_instance=RequestContext(request))
	else:
		documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
		if documentaryFiles:
			for docfile in documentaryFiles:
				dossierDoc.append({'title':docfile.title, 'description':docfile.description, 'url':docfile.image.url})
			
			my_data_dictionary['dossierDocs'].append(dossierDoc)
			logger.info(my_data_dictionary['dossierDocs'])

	# get user information here (documentary file ...)
	
	#
	return render_to_response('index.html', my_data_dictionary, context_instance=RequestContext(request))

def get_mesdossiersDoc(request):
	logger.info('get_mesdossiersDoc called')
	my_data_dictionary = {'user': request.user}
	my_data_dictionary['loginstatus'] = ''
	my_data_dictionary['myDocumentaryFiles'] = ''
	logger.info('get_mesdossiersDoc called2')
	if not request.user.is_authenticated():
		logger.info('Anonymous user')
		return render_to_response('index.html', my_data_dictionary, context_instance=RequestContext(request))
	else:
		logger.info('user'+str(request.user))
		documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
		if documentaryFiles:
			my_data_dictionary['myDocumentaryFiles'] = '<section id="dossierDoc"><h1>Mes dossiers docs</h1>'
			for docfile in documentaryFiles:
				my_data_dictionary['myDocumentaryFiles'] += '<article style="width:278px">'
				my_data_dictionary['myDocumentaryFiles'] += '<img src="{{ STATIC_URL }}images/'
				my_data_dictionary['myDocumentaryFiles'] += docfile.image.url
				my_data_dictionary['myDocumentaryFiles'] += '" style="height:60px;width:60px;float:left;padding-right:10px"/> <h2 style="float:left">'
				my_data_dictionary['myDocumentaryFiles'] += docfile.title
				my_data_dictionary['myDocumentaryFiles'] += '</h2><br><p>'
				my_data_dictionary['myDocumentaryFiles'] += docfile.description
				my_data_dictionary['myDocumentaryFiles'] += '</p></article>'

	# get user information here (documentary file ...)
	
	#
	return render_to_response('mesdossiersDoc.html', my_data_dictionary, context_instance=RequestContext(request))

	
def streamgraph(request):
	print 'streamgraph'
	if request.method == 'POST':
		print 'POST'
		searcher = Searcher(request);
		json = searcher.streamgraph()
		return HttpResponse(json)
	else:
		print 'ERROR'
		raise Http404
	return HttpResponse("OK")


def treemap(request):
	print 'TREEMAP ENTER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
	my_data_dictionary = {'user': request.user}
	my_data_dictionary['dossierDocs'] = []
	dossierDoc = []
	if request.user.is_authenticated():
		print request.user.is_authenticated()
		documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
		if documentaryFiles:
			for docfile in documentaryFiles:
				dossierDoc.append({'title':docfile.title, 'description':docfile.description, 'url':docfile.image.url})
			print dossierDoc
			my_data_dictionary['dossierDocs'].append(dossierDoc)
			logger.info(my_data_dictionary['dossierDocs'])

	searcher = Searcher(request);
	json = searcher.treemap()
	request.session['json'] = json
	if request.is_ajax():
		print("is_ajax")
		return HttpResponse(json)
	else:
		print("isnot_ajax")
		return render_to_response('recherche.html',my_data_dictionary, context_instance=RequestContext(request)) 


def get_documents_with_annotations(request,query=0,cluster=0,offset=0,count=0):
	print 'get_documents_with_annotations !!!!!!!!'

	'''if request.method == 'GET':'''
	if  request.method == 'GET' and request.session['refreshOnly'] == True:
		print("get_request and refresh")
		json2 = request.session['json2']
		request.session['refreshOnly'] = False
	else:
		print("NOT get_request and refresh")
		documents = Documents(request)
		json2 = documents.get_documents(query,cluster,offset,count)
		request.session['json2'] = json2
				
	d = json.loads(json2)
	my_data_dictionary = {'cluster_title': d['cluster_title']}
	my_data_dictionary['dossierDocs'] = []
	dossierDoc = []
	
	if request.user.is_authenticated():
		print request.user.is_authenticated()
		documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
		if documentaryFiles:
			for docfile in documentaryFiles:
				dossierDoc.append({'title':docfile.title, 'description':docfile.description, 'url':docfile.image.url})
			print dossierDoc
			my_data_dictionary['dossierDocs'].append(dossierDoc)
			logger.info(my_data_dictionary['dossierDocs'])
	
	if request.is_ajax():
		print("is_ajax")
		return HttpResponse(json2)
	else:
		print("isnot_ajax")
		return render_to_response('cluster.html',my_data_dictionary, context_instance=RequestContext(request))
	'''return HttpResponse(json)'''
	
	'''else:
		raise Http404'''
	
def get_annotations(request):
	if request.method == 'GET':
		print 'get_annotations'
		annotations = DocumentAnnotation(request);
		json = annotations.get_annotations()
		return HttpResponse(json)
	else:
		raise Http404	

@login_required
def documentary_files(request,myuser="",offset=0,count=0):
	print 'documentary_files'
	print request.user 
	if request.method == 'GET':
		doc_files = DocumentaryFiles(request);
		json = doc_files.get_files(myuser,offset,count)
		request.session['json3'] = json
		'''return HttpResponse(json)'''
		
		my_data_dictionary = {}
		my_data_dictionary['dossierDocs'] = []
		dossierDoc = []
		
		if request.user.is_authenticated():
			print request.user.is_authenticated()
			documentaryFiles = Documentaryfile.objects.filter(user=request.user.id)
			if documentaryFiles:
				for docfile in documentaryFiles:
					dossierDoc.append({'title':docfile.title, 'description':docfile.description, 'url':docfile.image.url})
				print dossierDoc
				my_data_dictionary['dossierDocs'].append(dossierDoc)
				logger.info(my_data_dictionary['dossierDocs'])
				
		return render_to_response('dossiersdocumentaire.html',my_data_dictionary, context_instance=RequestContext(request)) 
	else:
		raise Http404
		
def documentary_file_visibility(request):
	if request.method == 'POST':
		print 'documentary_file_visibility'
		documentary_file = DocumentaryFile(request);
		json = documentary_file.visibilityChange()		
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def documentary_file_delete(request):
	if request.method == 'POST':
		print 'documentary_file_delete'
		documentaryfile_var = DocumentaryFile(request);
		json = documentaryfile_var.delete()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def documentary_file_create(request):
	if request.method == 'POST':
		logger.info('documentary_file create')
		documentary_file = DocumentaryFile(request);
		json = documentary_file.create()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def cluster_annotation_create(request):
	if request.method == 'POST':
		logger.info('cluster annotation create')
		clusterAnnotation_var = ClusterAnnotation(request);
		json = clusterAnnotation_var.create()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def cluster_annotation_delete(request):
	if request.method == 'POST':
		logger.info('cluster annotation delete')
		clusterAnnotation_var = ClusterAnnotation(request);
		json = clusterAnnotation_var.delete()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def document_annotation_create(request):
	if request.method == 'POST':
		logger.info('document annotation create')
		document_annotation = DocumentAnnotation(request);
		json = document_annotation.create()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def document_annotation_delete(request):
	if request.method == 'POST':
		logger.info('document annotation delete')
		document_annotation = DocumentAnnotation(request);
		json = document_annotation.delete()
					
		return HttpResponse(json)
	else:
		raise Http404
	return HttpResponse("OK")

def get_clusters(request):
	if request.method == 'GET':
		logger.info('get clusters of a documentary file')
		clusters = Clusters(request);
		json = clusters.get_treemap_of_clusters()
					
		return HttpResponse(json)
	else:
		raise Http404

def create_annotation_on_documentary_file(request):
	if request.method == 'POST':
		logger.info('create an annotation on a documentary file')
		annotation = DocumentaryFileAnnotation(request);
		json = annotation.create()
					
		return HttpResponse(json)
	else:
		raise Http404
	
def delete_annotation_on_documentary_file(request):
	if request.method == 'POST':
		logger.info('delete an annotation on a documentary file')
		annotation = DocumentaryFileAnnotation(request);
		json = annotation.delete()
					
		return HttpResponse(json)
	else:
		raise Http404