from django.shortcuts import render
from itsapp.models import  Clan, ClanMembership, UserProfile
from django.contrib.auth.models import User
from django import forms
import string
from itsapp.utils import *
import os
import base64


USER_FIELD_SEPARATOR = ","
MAX_GROUP_IMAGE_SIZE = 1000000


def group(request):
	myclans = Clan.objects.filter(owner__exact=request.user.id)
	sharedclans = ClanMembership.objects.filter(user__exact=request.user.id)
	return render(request, 'itsapp/groups.html', {'myclans': myclans, 'sharedclans': sharedclans})



def group_detail(request,clan_id):
	clan = Clan.objects.get(id=clan_id);
	users = ClanMembership.objects.filter(clan__exact=clan.id)
	
	galleries=set()
	members=Permission.objects.filter(clan=clan)
	for mem in members:
		permission = PermissionUtil(request.user, mem.gallery.identificator)		
		if(permission.checkReadPermission()):
			galleries.add(mem.gallery)

	return render(request, 'itsapp/group_detail.html', {'clan': clan,'members': users,'group_galleries':galleries})

	

def group_new(request):
	if request.method == 'POST': # If the form has been submitted...
		form = GroupNewForm(request.POST, request.FILES) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
			# Process the data in form.cleaned_data
			name = form.cleaned_data['name']
			file = form.cleaned_data['file']

			try:
				exist = Clan.objects.get(name=name)
			except:
				exist = None

			if(exist==None):
				# group image
				try:
					# byl odeslan soubor?
					try:
						request.FILES['file'].size
						fileposted=True
					except:
						fileposted=False

					#kontrola velikosti
					if(fileposted and (request.FILES['file'].size > MAX_GROUP_IMAGE_SIZE)):
						msg = "Image is too large. Maximum size is " + MAX_GROUP_IMAGE_SIZE + " bytes."
						state = False
					else:
						clan = Clan(name=name, owner=request.user)
						clan.save()

						if(fileposted):
							filename = "group_"+name + "_" + request.FILES['file'].name + ".jpg"
							filename_tmp = "tmp_" + name + "_" + request.FILES['file'].name
							handle_uploaded_file(
								request.FILES['file'],
								filename,
								filename_tmp)
							cover=Photo(name=name,gallery=get_avatars_gallery(),path=ITSconf.VTA_data_root+"avatars/"+filename)
							cover.save()
							clan.cover_id=cover.id
							clan.save()
						else:
							clan.cover_id=-1
							clan.save()
				
						
						
						id_trans=createNewHistoryTransactionId()					
						saveActionToHistory(request.user,id_trans,"create_group",clan.id)

						msg = "Success."
						state = True
				except:
					msg = "Fail."
					state = True
			else:
				msg = "Group already exist. Use another name"
				state = False
		else:
			msg = "Validation error."
			state = False

		return render(request, 'itsapp/group_new.html', {
			'form': form,
			'state': state,
			'msg': msg
		})
	else:
		form = GroupNewForm() # An unbound form
		return render(request, 'itsapp/group_new.html', {
			'form': form,
		})


def handle_uploaded_file(file, filename, filename_tmp):
	#uloz v plne velikosti
    destination = open('media/groups/' + filename_tmp, 'wb+')
    for chunk in file.chunks():
        destination.write(chunk)
    destination.close()
    os.system("convert -resize 100X100 " + 'media/groups/' + filename_tmp + " " + ITSconf.VTA_data_root+"avatars/" + filename)
    os.system("rm " + 'media/groups/' + filename_tmp)
    


class GroupNewForm(forms.Form):
	name = forms.CharField( label="Group name" )
	file = forms.FileField( label="Group image", required=False )


def group_edit(request,clan_id):
	if request.method == 'POST': # If the form has been submitted...
		form = GroupEditForm(request.POST, request.FILES) # A form bound to the POST data
		clan = Clan.objects.get(id=clan_id)
		state = True

		if form.is_valid(): # All validation rules pass
			# Process the data in form.cleaned_data
			newname = form.cleaned_data['name']
			file = form.cleaned_data['file']

			try:
				exist = Clan.objects.get(name=newname)
			except:
				exist = None

			if(exist==None or newname==clan.name):
				cover=None
				try:
					cover=Photo.objects.get(id=clan.cover_id)
				except:
					cover=None
				# zmena obrazku
				if(file!=None):
					# kontrola velikosti
					if(request.FILES['file'].size > MAX_GROUP_IMAGE_SIZE):
						msg = "Image is too large. Maximum size is " + str(MAX_GROUP_IMAGE_SIZE) + " bytes."
						state = False		
						print 	"Image is too large. Maximum size is " + str(MAX_GROUP_IMAGE_SIZE) + " bytes."			
					else:
						filename = "group_"+newname + ".jpg"
						filename_tmp = "tmp_" + newname + "_" + request.FILES['file'].name
						handle_uploaded_file(
							request.FILES['file'],
							filename,
							filename_tmp)
						
						try:
							cover=Photo.objects.get(id=clan.cover_id)
							
						except:
							cover=Photo(gallery=get_avatars_gallery())
						try:
							os.system("rm "+cover.getThumbPath())
						except:
							print "rm error"
						cover.path=ITSconf.VTA_data_root+"avatars/"+filename
						cover.save()
						clan.cover_id = cover.id
						
				if(cover):
					cover.name="group-"+newname
					cover.save()
					print clan.cover_id
				clan.name = newname
				clan.save()
				id_trans=createNewHistoryTransactionId()					
				saveActionToHistory(request.user,id_trans,"update_group",clan.id)
				msg = "Success."
				state = True
			else:
				msg = "Group already exist. Use another name"
				state = False
			
		else:
			msg = "Validation error."
			state = False

		return render(request, 'itsapp/group_edit.html', {
			'form': form,
			'clan': clan,
			'state': state,
			'msg': msg
		})
	else:
		if(request.user.is_authenticated()):
			clan = Clan.objects.get(id=clan_id)
			cover_path=""
			try:
				cover=Photo.objects.get(id=clan.cover_id)
				cover_path=cover.path
			except:
				cover_path=""
			form = GroupEditForm(initial={'name': clan.name, 'cover': cover_path})

			return render(request, 'itsapp/group_edit.html', {
				'form': form,
				'clan': clan
			})
		else:
			return render(request, 'itsapp/group_edit.html', {})


class GroupEditForm(forms.Form):
	name = forms.CharField( label="Group name" )
	file = forms.FileField( label="Group image", required=False )


def group_invite(request,clan_id):
	clan = Clan.objects.get(id=clan_id)
	memberships = ClanMembership.objects.filter(clan=clan)
	if request.method == 'POST': # If the form has been submitted...
		form = GroupInviteForm(request.POST) # A form bound to the POST data

		if form.is_valid(): # All validation rules pass
			# Process the data in form.cleaned_data
			users = form.cleaned_data['users']
			try:
				userslist = string.split(users, USER_FIELD_SEPARATOR)
			except:
				userslist = []

			id_trans=createNewHistoryTransactionId()					
			#ClanMembership.objects.filter(clan=clan).delete()
			for u in userslist:
				try:
					user = User.objects.get(username=u)
					# pokud user neni v memberships, tak ho pridam
					try:
						ClanMembership.objects.get(clan=clan, user=user)
					except:
						membership = ClanMembership(clan=clan, user=user)
						membership.save()
						saveActionToHistory(request.user,id_trans,"add_user_to_group",str(clan.id)+" "+str(user.id))
				except:
					pass

			msg = "Success."
			state = True
		else:
			msg = "Validation error."
			state = False

		return render(request, 'itsapp/group_invite.html', {
			'form': form,
			'clan': clan,
			'memberships': memberships,
			'state': state,
			'msg': msg
		})
	else:
		if(request.user.is_authenticated()):
			clan = Clan.objects.get(id=clan_id)
			#memberships = ClanMembership.objects.filter(clan__exact=clan.id);
			#str=""
			#for c in memberships:
			#	str += c.user.username + USER_FIELD_SEPARATOR
			#form = GroupInviteForm(initial={'users': str})
			form = GroupInviteForm()

			return render(request, 'itsapp/group_invite.html', {
				'form': form,
				'clan': clan,
				'memberships': memberships,
			})
		else:
			return render(request, 'itsapp/group_invite.html', {})


class GroupInviteForm(forms.Form):
	users = forms.CharField( label="Users", widget=forms.Textarea )


def group_invite_delete(request,clan_id,user_id):
	try:
		clan=Clan.objects.get(id=clan_id)
		user=User.objects.get(username=user_id)
		ClanMembership.objects.get(clan=clan, user=user).delete()
		memberships = ClanMembership.objects.filter(clan=clan)
	except:
		pass

	if(request.user.is_authenticated()):
		form = GroupInviteForm()
		return render(request, 'itsapp/group_invite.html', {'form': form,'clan': clan, 'memberships': memberships})
	else:
		return render(request, 'itsapp/group_invite.html', {})


def group_delete(request,clan_id):
	group=Clan.objects.get(id=clan_id)
	if group.owner==request.user:
		members=ClanMembership.objects.filter(clan=group)
		members.delete()
		group.delete()
	return render(request, 'itsapp/group_delete.html',{'from':request.META.get('HTTP_REFERER', None) })
