from django.shortcuts import render, render_to_response
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.db.models import Max
from django.http import HttpResponse
from django.conf import settings
from debug import *
from permissions import *
import ITSconf
from itsapp.models import *

import os
import simplejson
### UTIL FUNCTION ###

## Function runs external native program 
# Program has to be placed in bin/ directory (defineds in ITSconf.py)
# app - name of program
# param - string of params
##
def run_native(app,param):
	print "run native function "+ app + " "+param
	os.environ['LD_LIBRARY_PATH'] = ITSconf.VTAPI_LIB_PATH
	print os.environ['LD_LIBRARY_PATH']
	p=os.popen(ITSconf.BIN_PATH+app+" "+param)
	response = p.readline()
	p.close()	
	return response


## Function runs external native program 
# Program has to be placed in bin/ directory (defineds in ITSconf.py)
# app - name of program
# param - string of params
##
def run_std_native(app,param):	
	p=os.popen(app+" "+param)
	response = p.readline()
	p.close()	
	return response


## Function creates thumbnail from original image. Thumbnail will be placed in media/thumbs/ directory
# path - path to original image
# hashname - name of thumbnail image 
##
def create_thumbnail(path,hash_name,width):
	os.system("mkdir "+settings.MEDIA_ROOT+"thumbs/"+width)
	print "create thumb for file:"+path+ " save to "+hash_name
	os.system("convert -resize "+ width+"X"+width+" \""+path+"\" "+hash_name)
	return


def render_error(request,error):
	return render(request,'itsapp/error.html',{'error': error})


##
# Function render Json result from dictionary
##
def render_json_data(request, dict_data):
	response_data = simplejson.dumps(dict_data)
	#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)


##
# Function returns admin user
##
def get_admin():
	return User.objects.get(username="admin")

##
# Function returns admin user
##
def get_unknow_avatar_id():
	avatar=None
	try:
		avatar=Photo.objects.get(name=";osdfo;irft309856klfdgj45896345ert534d6g5h5468768");
	except:
		avatar=Photo(name=";osdfo;irft309856klfdgj45896345ert534d6g5h5468768",path=settings.STATIC_ROOT+"img/admin_noavatar.jpg",gallery=get_avatars_gallery());
		avatar.save()

	return avatar.id
def get_unknown_img_path():
	return settings.STATIC_ROOT+"img/unknown.png"

##
# Function returns avatars gallery
##
def get_avatars_gallery():
	avatars_gallery=None
	try:
		avatars_gallery=Gallery.objects.get(identificator="avatars")
	except:
		os.mkdir(VTA_data_root+"avatars")
		avatars_gallery=Gallery(identificator="avatars",name="avatars",owner=get_admin())
		avatars_gallery.save()	
	return avatars_gallery

def createNewHistoryTransactionId():
	id_trans=HistoryItem.objects.all().aggregate(Max('id_transaction'))['id_transaction__max']
	if id_trans==None:
		id_trans=0
	else: 
		id_trans=id_trans+1
	return id_trans

def saveActionToHistory(user,transaction_id,action, params):
	h_item=HistoryItem(user=user,id_transaction=transaction_id,action=action,params=params)
	h_item.save()
