#Django imports
from django.shortcuts import render, render_to_response
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User, AnonymousUser
from django.db import IntegrityError
from django.db.models import Max
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django import forms


#Projects imports
from debug import *
from permissions import *
from itsapp.models import *
import ITSconf
from itsapp.utils import *

#python imports
import os
import simplejson
import base64
import shutil
import socket
import time
from random import *


def add_tags(request,gallery_id,photo_id,tags):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkWritePermission():
		if tags!="":
			p=None
			try:
				p=Photo.objects.get(id=photo_id)
			except:
				return render_error(request,"URL is corrupted!")

			gall=None
			try:
				gall=Gallery.objects.get(identificator=gallery_id)
			except:
				return render_error(request,"URL is corrupted!")
	
			if p.gallery!=gall:
				return render_error(request,"URL is corrupted!")

			pom=tags[:-1].replace(","," ")
			print pom
		
			id_trans=createNewHistoryTransactionId()

			response_data=run_native("update_tags",gallery_id+" "+p.getId()+" "+pom)
		
			print response_data

			'''
			tags_arr=pom.split(",")
			id_trans=createNewHistoryTransactionId()
			for tag in tags_arr:
				tag_num=int(tag)
				tag_id=str(abs(tag_num))
				print tag_id
				try:
					tag=Tag.objects.get(id=tag_id)		
					tag_type="1"
					if tag_num<0:tag_type=-1
					tagMember=TagMembership(tag=tag,photo=p,tag_type=tag_type)
					tagMember.save()
					saveActionToHistory(request.user,id_trans,"add_tag",photo_id+" "+ tag.identificator+" "+tag_type)
				except:
					print "tag is not in DB"
			'''
			'''tag=Tag.objects.get(id=tag_id)
		
			tagMember=TagMembership(tag=tag,photo=p,tag_type=tag_type)
			tagMember.save()
			id_trans=createNewHistoryTransactionId()
			saveActionToHistory(request.user,id_trans,"add_tag",photo_id+" "+ tag.identificator+" "+tag_type)
	'''
			return HttpResponse("ok", "mime/text")
		else:
			return HttpResponse("ok", "mime/text")
	else:
		return render_error(request,"Permission error")


def add_tag(request,gallery_id,photo_id,tag_id,tag_type):
	'''per=PermissionUtil(request.user,gallery_id)
	if per.checkWritePermission():
		p=None
		try:
			p=Photo.objects.get(id=photo_id)
		except:
			return render_error(request,"URL is corrupted!")

		gall=None
		try:
			gall=Gallery.objects.get(identificator=gallery_id)
		except:
			return render_error(request,"URL is corrupted!")
	
		if p.gallery!=gall:
			return render_error(request,"URL is corrupted!")
	
		tag=Tag.objects.get(id=tag_id)
		
		tagMember=TagMembership(tag=tag,photo=p,tag_type=tag_type)
		tagMember.save()
		id_trans=createNewHistoryTransactionId()
		saveActionToHistory(request.user,id_trans,"add_tag",photo_id+" "+ tag.identificator+" "+tag_type)
		return HttpResponse("ok", "mime/text")
	else:'''
	return render_error(request,"OLD FUNCTION")

def remove_tag(request,gallery_id,photo_id,tag_id):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkWritePermission():
		p=None
		try:
			p=Photo.objects.get(id=photo_id)
		except:
			return render_error(request,"URL is corrupted!")

		gall=None
		try:
			gall=Gallery.objects.get(identificator=gallery_id)
		except:
			return render_error(request,"URL is corrupted!")
	
		if p.gallery!=gall:
			return render_error(request,"URL is corrupted!")
		try:
			tag=Tag.objects.get(id=tag_id)
			tagMember=TagMembership.objects.filter(tag=tag,photo=p)
			id_trans=createNewHistoryTransactionId()
			for tm in tagMember:
				tm.delete()		
				saveActionToHistory(request.user,id_trans,"delete_tag",photo_id+" "+tag_id+" "+tm.tag_type)
		except Exception as exc:
			print "remove tag except "+str(exc)
		return HttpResponse("ok", "mime/text")
	else:
		return render_error(request,"Permission error")

def new_tag(request,tag_name):
	try:
		tag=Tag.objects.get(name=tag_name)
		return render_error(request,"Tag exist")
	except:
		tag=Tag(name=tag_name)
		tag.save()
		tag.identification=tag.id
		tag.save()		
		return HttpResponse("ok", "mime/text")
			

def get_all_tag_names(request):
	'''	
	result =dict()
	tags=Tag.objects.all()
	for tag in tags:		
		result[tag.id]=tag.name
	response_data = simplejson.dumps(result)
	'''
	response_data=run_native("get_tag_names","")

	if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
	    mimetype = 'application/json'
	else:
	    mimetype = 'text/plain'
	print('--------------------------------')
	return HttpResponse(response_data, mimetype=mimetype)

def get_tags(request,gallery_id,photo_id):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkReadPermission():
		p=None
		try:
			p=Photo.objects.get(id=photo_id)
		except:
			return render_error(request,"URL is corrupted!")

		gall=None
		try:
			gall=Gallery.objects.get(identificator=gallery_id)
		except:
			return render_error(request,"URL is corrupted!")
	
		if p.gallery!=gall:
			return render_error(request,"URL is corrupted!")
	
		'''result =dict()

		def tags_compare(x, y):	
		        return cmp(result[x][0],result[y][0])
		tags=TagMembership.objects.filter(photo=p).order_by('tag')
		for tag in tags:
			#t=Tag.objects.get(id=tag.id)
			result[tag.tag.id]=[tag.tag.name,tag.tag_type]
		sorted(result,cmp=tags_compare)
		response_data = simplejson.dumps(result)
		'''
		response_data=run_native("get_tags",gallery_id+" "+p.getId())
        
		#checking for json data type
		#big thanks to Guy Shapiro
		if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
		    mimetype = 'application/json'
		else:
		    mimetype = 'text/plain'
		print('--------------------------------')
		return HttpResponse(response_data, mimetype=mimetype)
	else:

		return render_error(request,"Permission error")

def get_local_tags(request,gallery_id,photo_id):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkReadPermission():
		p=None
		try:
			p=Photo.objects.get(id=photo_id)
		except:
			return render_error(request,"URL is corrupted!")

		gall=None
		try:
			gall=Gallery.objects.get(identificator=gallery_id)
		except:
			return render_error(request,"URL is corrupted!")
	
		if p.gallery!=gall:
			return render_error(request,"URL is corrupted!")
	
		result_tags=list()
		result_distance=list()
		i=0;
		position=0
		current_position=-1;
		#photos=Photo.objects.filter(gallery=gall).order_by("id")
		#for p in :
		#print type(photos)
		id_list = Photo.objects.raw("SELECT ROW_NUMBER() OVER(ORDER BY id DESC) AS 'Row Number' FROM itsapp_photo WHERE gallery_id="+str(gall.id))
		for photo_id in id_list:
			'''if photo_id==p.id:
				current_position=position
				break
			position+=1'''
			print photo_id

		start=current_position-10
		if start<0:start=0
		end= current_position+10
		if end>= position:end=position-1

		for idx in range(start,end):
			picture=Photo.objects.get(id=id_list[idx])
			if picture!=p:
				tags=TagMembership.objects.filter(photo=picture)
				for tag in tags:
					#t=Tag.objects.get(id=tag.id)
					if tag.tag.identificator!="":
						tag_type=int(tag.tag_type)
						result_tags.append(tag_type*int(tag.tag.identificator))
						result_distance.append(idx)
				
		if len(result_tags)!=0:
			response_data="local_tags:"
			for tag in result_tags:
				response_data+=str(tag)+","		
			response_data=response_data[:-1]+";local_tags_distance:"		
			
			#prepocet vzdalenosti
			for i in range(len(result_tags)):
				response_data+=str(result_distance[i]-current_position)+","



			return HttpResponse(response_data, mimetype='text/plain')
		else:
			return HttpResponse("", mimetype='text/plain')
	else:

		return render_error(request,"Permission error")

##
# Funkce parsuje posledni radek nize zmineneho souboru a vraci pole ID jinak None (v pripae ze ma radek spatny format popripade spatne request_id)
##
def get_parse_last_line(request_id):
	respon=run_std_native("tail","-n1 /home/ilanik/its/suggestion/suggestion_responses").replace("\n","")
	root_arr=respon.split(";")
	if(len(root_arr)!=2):return None

	response_id=root_arr[0].split(":")[1]
	if request_id!=response_id:
		return None

	return root_arr[1].split(",")

	

def get_suggestion(request,gallery_id,photo_id,current_suggestion,suggestions_count):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkReadPermission():
		p=None
		try:
			p=Photo.objects.get(id=photo_id)
		except:
			return render_error(request,"URL is corrupted!")

		gall=None
		try:
			gall=Gallery.objects.get(identificator=gallery_id)
		except:
			return render_error(request,"URL is corrupted!")
	
		if p.gallery!=gall:
			return render_error(request,"URL is corrupted!")
	
		

		'''def tags_compare(x, y):	
		        return cmp(result[x][0],result[y][0])'''
		tags=TagMembership.objects.filter(photo=p)
		positive_set=set()
		negative_set=set()
		for tag in tags:
			if tag.tag.identificator!="":
				if tag.tag_type=="1":
					positive_set.add(tag.tag.identificator)
				else:
					negative_set.add(tag.tag.identificator)
			else:
					positive_set.add(tag.tag.id)
		
		positive_tags=""
		negative_tags=""

		for it in positive_set:positive_tags=positive_tags+str(it)+","
		for it in negative_set:negative_tags=negative_tags+str(it)+","
		if len(positive_tags)!=0:positive_tags=positive_tags[:-1] 
		if len(negative_tags)!=0:negative_tags=negative_tags[:-1] 

		

		
		request_id=str(randint(0, 312354));

		process_line="/home/ilanik/its/suggestion/send_suggestion.sh merlin.fit.vutbr.cz 7333 'request_id:"+request_id+";";
		if len(positive_set)!=0:
			process_line=process_line+"positive:"+positive_tags+";"

		if len(negative_set)!=0:
			process_line=process_line+"negative:"+negative_tags+";"

		current_tags=""		
		if(current_suggestion!=""):
			tmp_arr=current_suggestion[:-1].split(",")
			for tag in tmp_arr:
				try:
					t=Tag.objects.get(id=tag)
					current_tags=current_tags+t.identificator+","
				except:
					pass
				
			process_line=process_line+"current_suggestions:"+current_tags[:-1]+";"
			
		
		
		process_line=process_line+"output_size:"+suggestions_count+";end_request'"
		print process_line

		#spusti se davka a v souboru root/suggestion/suggestion_responces se objevi odpoved		
		os.system(process_line)
		respon_arr=get_parse_last_line(request_id)
		
		counter=0
		

		while(respon_arr==None):
			time.sleep(1)
			respon_arr=get_parse_last_line(request_id)	
			counter+=1
			if counter>5 :
				print "request error"
				return render_error(request,"internal error!")
		print respon_arr
		
		'''
		result =dict()
		for tag_id in respon_arr:
			
			try:
				tag=Tag.objects.get(identificator=tag_id)
				result[tag.id]=[tag.name,1]
			except Exception as e:
				print "tag "+tag_id +" is not in DB"+ str(e)

		response_data = simplejson.dumps(result)
		'''
		response_data = simplejson.dumps(respon_arr)
		#checking for json data type
		if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
		    mimetype = 'application/json'
		else:
		    mimetype = 'text/plain'
		return HttpResponse(response_data, mimetype=mimetype)
    	else:
		return render_error(request,"Permission error")
    

