#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, AnonymousUser
from django.db import IntegrityError
from django.http import HttpResponse
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
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





### WIEWS FUNCTION ###


def syncwithvt(request):
	admin=get_admin()
	if request.user==admin:
		sequences=[]

		if request.method == 'POST': # If the form has been submitted...
			d = {}
			d.update(csrf(request))
			for item in request.POST:
				if(item!="csrfmiddlewaretoken"):
					#Vytvoreni nove galerie
					id_trans=createNewHistoryTransactionId()					

					new_gall=Gallery(name=item,identificator=item,owner=admin,cover="/")
					new_gall.save()
					saveActionToHistory(request.user,id_trans,"create_gallery",item)

					public_clan=Clan.objects.get(name="Public")
					permmission=Permission(gallery=new_gall,clan=public_clan,permission=0)
					permmission.save()
					saveActionToHistory(request.user,id_trans,"create_permission",permmission.id)
					
					#Vytvoreni fotek v galerii
					response=run_native("get_images",item)
					try:
						json_response=	simplejson.loads(response)
						for img in json_response["sequence"]["imgs"]:
							path=img["path"]
							tmp=path.split("/")
							photo=Photo(path=path,name=tmp[len(tmp)-1],gallery=new_gall,b64path=base64.b16encode(path))
							photo.save()
							saveActionToHistory(request.user,id_trans,"create_photo",photo.id)
					except:
						return render_error(request,"Json get_images error")

			
			return HttpResponseRedirect(reverse('galleries'))
		else:
			

			response=run_native("get_seqvences","")
			json_response=	simplejson.loads(response)
			for seq in json_response["sequences"]:
				try:
					Gallery.objects.get(identificator=seq["name"])
				except:
					sequences.append(seq["name"])
		
			return render(request,'itsapp/admin_special_syncwithvt.html', {'sequences':sequences})
		#return render_error(request,response)
	else:
		return render_error(request,"This page is accessible only for admins account!")

def import_annotation(request):
	admin=get_admin()
	if request.user==admin:
		sequences=[]

		if request.method == 'POST': # If the form has been submitted...
			d = {}
			d.update(csrf(request))
			for item in request.POST:
				if(item!="csrfmiddlewaretoken"):

					id_trans=createNewHistoryTransactionId()					

					gall=Gallery.objects.get(identificator=item)
					photos=Photo.objects.filter(gallery=gall)
					size=len(photos)
					photo_counter=0
					block_size=100
					iteration_count=len(photos)/block_size
					for i in range(iteration_count):
						response=run_native("get_tags_from_sequence",gall.identificator+" "+str(i*block_size)+" "+str(block_size))
						json_response=	simplejson.loads(response)
						for img in json_response["sequence"]["imgs"]:
							try:
								photo=photos.get(name=img["name"])
								#print photo
								idx=0
								for tagResponse in img["tags"]:
									if tagResponse!="0":
										tag=Tag.objects.get(identificator=idx)
										tagmember=None
										try:
											tagmember=TagMembership.objects.get(tag=tag,photo=photo)
											tagmember.tag_type=tagResponse
										except:
											tagmember=TagMembership(tag=tag,photo=photo,tag_type=tagResponse)		
										tagmember.save()
										saveActionToHistory(request.user,id_trans,"add_tag",str(photo.id)+" "+tag.identificator+" "+tagResponse)
								
								idx+=1
							except Exception as e:
								print "chybi obrazek "+img["name"]
						print i+" from "+str(iteration_count)+" "+str(int((i*100)/iteration_count))+"%"


								
			return HttpResponseRedirect(reverse('admin_page'))
		else:
			

			response=run_native("get_seqvences","")
			json_response=	simplejson.loads(response)
			for seq in json_response["sequences"]:
				sequences.append(seq["name"])
		
			return render(request,'itsapp/admin_special_import_annotation.html', {'sequences':sequences})
		#return render_error(request,response)
	else:
		return render_error(request,"This page is accessible only for admins account!")

def importTrecvidClass(request):
	f = open('iacc.1.tv11.devel.class', 'r')
	idx=0
	for line in f.readlines():
		name=line.split("\t")[0]
		tag=Tag(name=name,description=name,identificator=str(idx))
		tag.save()
		idx=idx+1
	return render_error(request,"Done!")

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

def get_all_gall_ids(request):
	galleries=Gallery.objects.all()
	result=""
	for seg in galleries:
		result+=str(seg.identificator)+","
	result=result[:-1]

	return HttpResponse(result, mimetype='text/plain')


