#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 time





### WIEWS FUNCTION ###

#oprava coveru
def checkCover(gallery):
	try:
		Photo.objects.get(id=gallery.cover_id)
	except:
		try:
			cover=Photo.objects.filter(gallery=gallery)[1]
			gallery.cover_id=cover.id
			gallery.save()
		except:
			gallery.cover_id="-1"	


#
# View for all available galleries
#
def user_info(request,user_id):
	#response=run_native("get_seqvences","")
	#json_response=	simplejson.loads(response)


	mygalleries=[]
	shared_galleries=set()

	if type(request.user)!=AnonymousUser:
		# moje galerie
		mygalleries=Gallery.objects.filter(owner=request.user)
		for gallery in mygalleries:
			#oprava coveru
			checkCover(gallery)

		# sdilene galerie
		# projiti vsech skupin ve kterych je uzivatel clen
		members=ClanMembership.objects.filter(user=request.user)
		for member in members:
			permissions=Permission.objects.filter(clan=member.clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(request.user, per.gallery.identificator)
					clan_permit_read = permission.checkClanReadPermission(member.clan)
					if(clan_permit_read):
						shared_galleries.add(per.gallery)

		# projiti vsech skupin u kterych je uzivatel vlastnik
		my_clans=Clan.objects.filter(owner=request.user)
		for clan in my_clans:
			permissions=Permission.objects.filter(clan=clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(request.user, per.gallery.identificator)
					clan_permit_read = permission.checkClanReadPermission(clan)
					if(clan_permit_read):
						shared_galleries.add(per.gallery)

		# projiti public skupiny
		public_clan=Clan.objects.get(name="Public")
		permissions=Permission.objects.filter(clan=public_clan)
		for permission in permissions:
			if(permission.gallery.owner==request.user):
				continue
			permissionUtil = PermissionUtil(request.user, permission.gallery)
			clan_permit_read = permissionUtil.checkClanReadPermission(public_clan)
			if(clan_permit_read):
				shared_galleries.add(permission.gallery)




	else:
		# projiti public skupiny
		public_clan=Clan.objects.get(name="Public")
		permissions=Permission.objects.filter(clan=public_clan)
		for permission in permissions:
			permissionUtil = PermissionUtil(None, permission.gallery)
			clan_permit_read = permissionUtil.checkClanReadPermission(public_clan)
			if(clan_permit_read):
				shared_galleries.add(permission.gallery)




	# oprava coveru
	for gallery in shared_galleries:
		checkCover(gallery)

	return render(request,'itsapp/galleries.html', {'mygalleries': mygalleries, 'sharedgalleries': shared_galleries})

#
# View for all available galleries
#
def galleries(request):
	#response=run_native("get_seqvences","")
	#json_response=	simplejson.loads(response)


	mygalleries=[]
	shared_galleries=set()

	if type(request.user)!=AnonymousUser:
		# moje galerie
		mygalleries=Gallery.objects.filter(owner=request.user)
		for gallery in mygalleries:
			#oprava coveru
			checkCover(gallery)

		# sdilene galerie
		# projiti vsech skupin ve kterych je uzivatel clen
		members=ClanMembership.objects.filter(user=request.user)
		for member in members:
			permissions=Permission.objects.filter(clan=member.clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(request.user, per.gallery.identificator)
					clan_permit_read = permission.checkClanReadPermission(member.clan)
					if(clan_permit_read):
						shared_galleries.add(per.gallery)

		# projiti vsech skupin u kterych je uzivatel vlastnik
		my_clans=Clan.objects.filter(owner=request.user)
		for clan in my_clans:
			permissions=Permission.objects.filter(clan=clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(request.user, per.gallery.identificator)
					clan_permit_read = permission.checkClanReadPermission(clan)
					if(clan_permit_read):
						shared_galleries.add(per.gallery)

		# projiti public skupiny
		public_clan=Clan.objects.get(name="Public")
		permissions=Permission.objects.filter(clan=public_clan)
		for permission in permissions:
			if(permission.gallery.owner==request.user):
				continue
			permissionUtil = PermissionUtil(request.user, permission.gallery)
			clan_permit_read = permissionUtil.checkClanReadPermission(public_clan)
			if(clan_permit_read):
				shared_galleries.add(permission.gallery)




	else:
		# projiti public skupiny
		public_clan=Clan.objects.get(name="Public")
		permissions=Permission.objects.filter(clan=public_clan)
		for permission in permissions:
			permissionUtil = PermissionUtil(None, permission.gallery)
			clan_permit_read = permissionUtil.checkClanReadPermission(public_clan)
			if(clan_permit_read):
				shared_galleries.add(permission.gallery)




	# oprava coveru
	for gallery in shared_galleries:
		checkCover(gallery)

	return render(request,'itsapp/galleries.html', {'mygalleries': mygalleries, 'sharedgalleries': shared_galleries})

def gallery_new(request):
	return render(request,'itsapp/gallery_new.html')

def gallery_remove(request,gallery_id):
	#print "remove data from VTAPI db"
	#response=run_native("remove_sequence",gallery_id)
	#TODO PRAVA
	
	gallery=Gallery.objects.get(identificator=gallery_id)
	id_trans=createNewHistoryTransactionId()

	photos=Photo.objects.filter(gallery=gallery)
	for photo in photos:
		photo_id=photo.id
		photo.delete()
		saveActionToHistory(request.user,id_trans,"delete_photo",photo_id)

	gallery.delete()
	saveActionToHistory(request.user,id_trans,"delete_gallery",gallery_id)

	permissions=Permission.objects.filter(gallery=gallery_id)
	for permission in permissions:	
		per_id=permission.id
		permission.delete()
		saveActionToHistory(request.user,id_trans,"delete_permission",per_id)
	

	return HttpResponseRedirect(reverse('galleries'))
	


def gallery_detail2(request,gallery_id,page,edit_gallery):
	per=PermissionUtil(request.user,gallery_id)
	if per.checkReadPermission():

		table=[]
		table.append([])
		g=Gallery.objects.get(identificator=gallery_id)
		try:
			counter=0
			img_count=0
			print "page:"+str(page)
			img_start=int(int(page)*int(ITSconf.IMG_PER_PAGE))
			img_end=int((int(page)+1)*int(ITSconf.IMG_PER_PAGE))
			print "s:"+str(img_start)+" end:"+str(img_end)
			photos_selection=Photo.objects.filter(gallery=g).order_by("id")[img_start:img_end]
			#photos_selection=photos[img_start:img_end]
		
			for photo in photos_selection:
				if counter % 3 == 0:
					table.append([])			
				table[counter / 3].append(photo)
				counter=counter+1

			img_count=Photo.objects.filter(gallery=g).count()

			end_page= (img_count/int(ITSconf.IMG_PER_PAGE))

			prev_page=(int(page)-1)
			if prev_page<0: prev_page=0

			next_page=(int(page)+1)
			if next_page>end_page: next_page=end_page	
		

			return render(request,'itsapp/gallery_detail.html', 
				{'gallery_name': g.name,
				'gallery_id': g.identificator,
				'photo_ids':table,
				'page':page,
				'page_prev':prev_page,
				'page_next':next_page,
				'page_end':end_page,
				'edit_gallery':edit_gallery})
		except Exception as expt:
			#raise expt
			#print "Internal error: get images json error:\n"+str(expt)+"\n"+response	
		
			return render_error(request,"Internal error:"+str(expt))
	else:
		return render_error(request,"Permission error")

def gallery_detail_page(request,gallery_id,page):	
	return 	gallery_detail2(request,gallery_id,page,0)


def gallery_detail(request,gallery_id):	
	return 	gallery_detail_page(request,gallery_id,0)









def gallery_permissions(request,gallery_id):
	gallery=Gallery.objects.get(identificator=gallery_id)
	permissions=Permission.objects.filter(gallery=gallery)


	# zjistim, zda mam prava editovat galerii
	clan_permit_write = False
	if(gallery.owner==request.user):
		clan_permit_write = True
	else:
		pass

		"""
		# projiti vsech skupin ve kterych je uzivatel clen
		members=ClanMembership.objects.filter(user=request.user)
		for member in members:
			permissions=Permission.objects.filter(clan=member.clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(per.gallery.identificator)
					clan_permit_write = permission.checkClanWritePermission(member.clan)

		# projiti vsech skupin u kterych je uzivatel vlastnik
		my_clans=Clan.objects.filter(owner=request.user)
		for clan in my_clans:
			permissions=Permission.objects.filter(clan=clan)
			for per in permissions:
				if(per.gallery.owner!=request.user):
					permission = PermissionUtil(per.gallery.identificator)
					clan_permit_write = permission.checkClanReadPermission(clan)
		"""



		

	#TODO
	"""
	else:
		for p in permissions:
			clan = p.clan
			permission = p.permission
			try:
				memberships=ClanMembership.object.get(user=request.user, clan=clan)
				permit = True
				break
			except:
				continue
	"""
	
	# uzivatel nema prava editovat
	if(not clan_permit_write):
		return render(request, 'itsapp/gallery_permissions.html', {
			'permit': clan_permit_write,
		})

	if request.method == 'POST':
		form1 = GalleryEditNameForm(request.POST)
		form2 = GalleryEditPermissionForm(request.POST)

		if 'formname' in request.POST:
			form2 = GalleryEditPermissionForm()
			if form1.is_valid():
				name = form1.cleaned_data['name']

				# test zda galerie existuje
				try:
					galleryExist=Gallery.objects.get(name=name,owner=request.user)
					msg = "Fail. Gallery name already exists for current user."
					state = False
				except:
					gallery.name = name
					gallery.save()
					msg = "Success."
					state = True
			else:
				msg = "Validation error."
				state = False

		elif 'formpermission' in request.POST:
			form1 = GalleryEditNameForm(initial={'name': gallery.name})
			if form2.is_valid():
				group = form2.cleaned_data['group']
				permission = form2.cleaned_data['permission']

				clan=Clan.objects.get(name=group)

				# test zda permission existuje
				try:
					permissionExist=Permission.objects.get(gallery=gallery,clan=clan)
					msg = "Fail. Permission already exists."
					state = False
				except:
					try:
						permissionObject = Permission(gallery=gallery, clan=clan, permission=permission)
						permissionObject.save()
						msg = "Success."
						state = True
					except:
						msg = "Group name doesn't exist."
						state = False
			else:
				msg = "Validation error."
				state = False

		return render(request, 'itsapp/gallery_permissions.html', {
			'form1': form1,
			'form2': form2,
			'permissions': permissions,
			'gallery': gallery,
			'permit': clan_permit_write,
			'state': state,
			'msg': msg
		})

	else:
		if(request.user.is_authenticated()):
			form1 = GalleryEditNameForm(initial={'name': gallery.name})
			form2 = GalleryEditPermissionForm()
			return render(request, 'itsapp/gallery_permissions.html', {
				'form1': form1,
				'form2': form2,
				'permissions': permissions,
				'permit': clan_permit_write,
				'gallery': gallery
			})
		else:
			return render(request, 'itsapp/gallery_permissions.html', {})


def gallery_permissions_remove(request,gallery_id,permission_id):
	#gallery=Gallery.objects.get(identificator=gallery_id)
	permission=Permission.objects.get(id=permission_id)
	permission.delete()
	return render(request, 'itsapp/gallery_permissions_remove.html', {})






class GalleryEditNameForm(forms.Form):
	name = forms.CharField( label="Name" )

class GalleryEditPermissionForm(forms.Form):
	group = forms.CharField( label="Group name" )
	permission = forms.CharField(max_length=3, widget=forms.Select(choices=PermissionUtil.PERMISSIONS_CHOICES))





def gallery_edit_photos(request,gallery_id):
	return 	gallery_detail2(request,gallery_id,0,1)


def gallery_edit_page(request,gallery_id,page):	
	return 	gallery_detail2(request,gallery_id,page,1)


class NewTagForm(forms.Form):
	name = forms.CharField( label="Name" )

def show_photo(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!")
	
		try:
			prev=Photo.objects.filter(id__lt=photo_id).order_by("-id")[0]
			if(prev.gallery==None):
				prev=None
			elif prev.gallery.identificator != gallery_id:
				prev=None
		except:
			prev=None
		try:
			next=Photo.objects.filter(id__gt=photo_id)[0]
			if(next.gallery==None):
				next=None
			elif next.gallery.identificator != gallery_id:
				next=None
		except:
			next =None

		
		return render(request,'itsapp/photo.html', {'gallery': gall,'photo':p,'prev_photo':prev,'next_photo':next})
	else:
		return render_error(request,"Permission error")


def photo_delete(request,gallery_id,photo_id):

	#TODO OPRAVNENI
	p=Photo.objects.get(id=photo_id)
	p.delete()

	id_trans=createNewHistoryTransactionId()
	saveActionToHistory(request.user,id_trans,"delete_photo",photo_id)
	
	return HttpResponseRedirect(reverse('gallery_edit_photos',kwargs={'gallery_id':gallery_id}))


def photo_edit(request,gallery_id,photo_id):
	p=Photo.objects.get(id=photo_id)
	return render(request,'itsapp/photo.html', {'gallery_id': gallery_id,'photo_id':p.id})

### FUNCTIONS RETURNS BINARY DATA ###

def get_image_data(request,photo_id):	

	p=Photo.objects.get(id=photo_id)
	image_data = open(p.path, 'rb').read()
	return HttpResponse(image_data, mimetype='image/jpg')


def get_thumb_data(request,path,width):	

	
	file_path=settings.MEDIA_ROOT+"thumbs/"+width+"/"+path
	try:
		image_data = open(file_path, 'rb').read()
	except IOError:
		create_thumbnail("/home/ilanik/its/mnt/"+path,file_path,width)
		image_data = open(file_path, 'rb').read()	
	return HttpResponse(image_data, mimetype='image/jpg')

def get_thumb_data2(request,photo_id,width):
	#TOTO prava	
	p=Photo.objects.get(id=photo_id)

	


	path=""
	if(os.path.isfile(p.path)):
		path=p.getThumbPath(width)
	else:
		#path=get_unknown_img_path()
		pass
	try:
		print "load "+ path
		os.system("mkdir "+p.getThumbDir(width))
		image_data = open(path, 'rb').read()
	except IOError:
		create_thumbnail(p.path,path,width)
		image_data = open(path, 'rb').read()	
	return HttpResponse(image_data, mimetype='image/jpg')


def get_avatar_data(request,what,what_id):
	path=""
	if what=="user":
		user=User.objects.get(id=what_id)
		profil=UserProfile.objects.get(user=user)
		path=Photo.objects.get(id=profil.avatar).path
	elif what=="group":
		#clan=Clan.objects.get(id=what_id)
		#path=settings.MEDIA_ROOT+"avatars/"+clan.avatar
		path=Photo.objects.get(id=what_id).path
	try:
		image_data = open(path, 'rb').read()
	except:
		image_data = open(settings.STATIC_ROOT+"img/admin_noavatar.jpg", 'rb').read()

	return HttpResponse(image_data, mimetype='image/jpg')


def get_thumb_data_simple(request,path):
	return get_thumb_data(request,path,ITSconf.THUMB_SIZE)


