#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





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



def user_page(request,user_id):

	user_galleries=set()

	user=User.objects.get(id=user_id)
	userProfile=UserProfile.objects.get(user=user)

	# uzivatelovy galerie
	mygalleries=Gallery.objects.filter(owner=user)
	for gallery in mygalleries:		
		permission = PermissionUtil(request.user, gallery.identificator)		
		if(permission.checkReadPermission()):
			#oprava coveru
			checkCover(gallery)
			user_galleries.add(gallery)

	groups=set()
	user_clans=Clan.objects.filter(owner=user)
	for clan in user_clans:
		groups.add(clan)
	members=ClanMembership.objects.filter(user=user)
	for member in members:
		groups.add(member.clan)



	return render(request,'itsapp/user_page.html', {'userProfile':userProfile,'user_galleries': user_galleries,'user_groups':groups})


