#Django imports
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.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404
from django import forms
from django.template import RequestContext
from django.core.files.uploadedfile import UploadedFile
from django.conf import settings
from django.utils import simplejson

#Other library kimports
from multiuploader.models import MultiuploaderImage
from sorl.thumbnail import get_thumbnail

#Python imports
import random
import shutil
import os

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

class AlbumNewForm(forms.Form):
	name = forms.CharField( label="Album name", required=True )


def create_empty_gallery(request):
	img_path=settings.MEDIA_ROOT+"upload_imgs/"+str(request.user)

	if request.method == 'POST': # If the form has been submitted...
		form = AlbumNewForm(request.POST) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
			name = form.cleaned_data['name']
			

			# test zda galerie existuje
			try:
				gallery=Gallery.objects.get(name=name,owner=request.user)
				msg = "Fail. Gallery name already exists for current user."
				state = False
			except:
				response=run_native("create_new_sequence","")						
				json_response=	simplejson.loads(response)
				gallery=Gallery(name=name,identificator=json_response["sequence"]["name"],owner=request.user,cover_id="-1")
				gallery.save()
				id_trans=createNewHistoryTransactionId()	
				saveActionToHistory(request.user,id_trans,"create_gallery",gallery.identificator)

				public_clan=Clan.objects.get(name="Public")
				try:
					permmission=Permission.objects.get(gallery=gallery,clan=public_clan)
				except:
					permmission=Permission(gallery=gallery,clan=public_clan,permission=0)
					permmission.save()
					saveActionToHistory(request.user,id_trans,"create_permission",permmission.id)

				return HttpResponseRedirect(reverse('add_photo',kwargs={'gallery_id':gallery.identificator}))
								
		else:
			msg = "Validation error."
			state = False

		return render(request, 'itsapp/upload.html', {
			'form': form,
			'msg': msg,
			'state': state,
		})

	else:
		#preventivni smazani obsahu tempoveho adresare (kdyby tam neco nahodou zbylo odposledne)
		print "remove temp img folder"
		try:
			shutil.rmtree(img_path)
		except Exception as expt:
			print expt

		form = AlbumNewForm() # An unbound form
		return render(request,'itsapp/upload.html',{'form':form} )

def upload(request):
	#cesta k docasnemu uploadovacimu adresari
	img_path=settings.MEDIA_ROOT+"upload_imgs/"+str(request.user)

	if request.method == 'POST': # If the form has been submitted...
		form = AlbumNewForm(request.POST) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
			name = form.cleaned_data['name']
			

			# test zda galerie existuje
			try:
				gallery=Gallery.objects.get(name=name,owner=request.user)
				msg = "Fail. Gallery name already exists for current user."
				state = False
			except:
				msg = "Success."
				state = True
				return render(request, 'itsapp/upload_add_photos.html', {
					'gallery_name':name
				})
								
		else:
			msg = "Validation error."
			state = False

		return render(request, 'itsapp/upload.html', {
			'form': form,
			'msg': msg,
			'state': state,
		})

	else:
		#preventivni smazani obsahu tempoveho adresare (kdyby tam neco nahodou zbylo odposledne)
		print "remove temp img folder"
		try:
			shutil.rmtree(img_path)
		except Exception as expt:
			print expt

		form = AlbumNewForm() # An unbound form
		return render(request,'itsapp/upload.html',{'form':form} )

def add_photo(request,gallery_id):
	gallery=Gallery.objects.get(identificator=gallery_id)
	return render(request, 'itsapp/upload_add_photos.html', {
		'gallery_id':gallery.identificator
	})

def upload_post_processing(request,gallery_id):
	return render(request,'itsapp/upload_post_processing.html',{'gallery_id':gallery_id})

def upload_finish(request,gallery_id):
	#cesta k docasnemu uploadovacimu adresari
	img_path=settings.MEDIA_ROOT+"upload_imgs/"+str(request.user)
	gallery=None
	try:
		gallery=Gallery.objects.get(identificator=gallery_id,owner=request.user)	
	except:		
		return render_error(request,"Internal error: gallery not exist")

	response=run_native("upload_photo",gallery.identificator+" "+img_path)				
	json_response=	simplejson.loads(response)
	gallery_id=json_response["sequence"]["id"]
	upload_items=json_response["sequence"]["imgs"]	

	print "upload galery_id:"+gallery_id+" imgs count:"+str(len(upload_items))
			
	try:
		dst_path=ITSconf.VTA_data_root+gallery_id
		print "create dir:"+dst_path	
		try:
			os.mkdir(dst_path)
		except Exception as e: 
			print "dir exist " + str(e)
			
		id_trans=createNewHistoryTransactionId()
		print "move files from "+img_path+" to "+dst_path		
		for file in upload_items:
			print "copy "+img_path+"/"+file["path"] +" to "+ dst_path+"/"+file["new_name"]
			photo_path=dst_path+"/"+file["new_name"]
			photo=Photo(name=file["path"],path=photo_path,gallery=gallery)
			photo.save()
			saveActionToHistory(request.user,id_trans,"create_photo",photo.id)
			print "create django db item "+str(photo)
			shutil.copy(img_path+"/"+file["path"], dst_path+"/"+file["new_name"])
		
		#shutil.copytree(img_path,dst_path)
		
	except Exception as expt:
		print expt	
	finally:
		print "remove dir:"+img_path	
		try:
			shutil.rmtree(img_path)				
		except Exception as e:
			print e
			
				
	return HttpResponseRedirect(reverse('gallery_detail',kwargs={'gallery_id':gallery.identificator}))
	
	

def upload_success(request):
	return render(request,'itsapp/message.html',{'message':'upload file success'})


