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, check_password
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from itsapp.models import UserProfile
from itsapp.utils import *
import os
import base64

import ITSconf


MAX_AVATAR_SIZE = 1000000


### REGISTRATE #######################################################################


def registrate_user(request):
	if request.method == 'POST': # If the form has been submitted...
		form = RegistrateForm(request.POST) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
			# Process the data in form.cleaned_data
			username = form.cleaned_data['username']
			email = form.cleaned_data['email']
			password1 = form.cleaned_data['password1']
			password2 = form.cleaned_data['password2']

			if password1!=password2:
				msg = "Password control failed."
				state = False
			else:
				try:
					# vytvoreni noveho uzivatele
					user = User.objects.create_user(username, email, password1)
					
					# prihlaseni
					user = authenticate(username=username, password=password1)

					# vytvoreni profilu
					profile = UserProfile(user=user, avatar="")
					profile.save()

					if user is not None:
						if user.is_active:
							login(request, user)
							# redirect to a success page.
							msg="Success."
							state = True
						else:
							# return a 'disabled account' error message
							msg="Disabled account."
							state = False
					else:
						# return an 'invalid login' error message.
						msg="Invalid login."
						state = False

				except IntegrityError:
					msg = "Integrity error. Use another username."
					state = False
		else:
			msg = "Validation error."
			state = False

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

		return render(request, 'itsapp/registration.html', {
			'form': form,
		})


class RegistrateForm(forms.Form):
	username = forms.CharField( label="Username" )
	email = forms.EmailField( label="E-mail" )
	password1 = forms.CharField( widget=forms.PasswordInput, label="Password" )
	password2 = forms.CharField( widget=forms.PasswordInput, label="Password confirmation" )


### LOGIN #######################################################################


def login_user(request):
	if request.method == 'POST': # If the form has been submitted...
		form = LoginForm(request.POST) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
			# Process the data in form.cleaned_data
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']

			user = authenticate(username=username, password=password)

			if user is not None:
				if user.is_active:
					login(request, user)
					# redirect to a success page.
					msg="Success."
					state = True
				else:
					# return a 'disabled account' error message
					msg="Disabled account."
					state = False
			else:
				# return an 'invalid login' error message.
				msg="Invalid login."
				state = False
		else:
			msg = "Validation error."
			state = False

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

		return render(request, 'itsapp/login.html', {
			'form': form,
		})


class LoginForm(forms.Form):
	username = forms.CharField( label="Username" )
	password = forms.CharField( widget=forms.PasswordInput, label="Password" )


### LOGOUT #######################################################################


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


### SETTINGS #######################################################################


def settings_user(request):
	if request.method == 'POST': # If the form has been submitted...
		form = SettingsForm(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
			email = form.cleaned_data['email']
			current_password = form.cleaned_data['current_password']
			new_password = form.cleaned_data['new_password']
			new_password_confirm = form.cleaned_data['new_password_confirm']
			file = form.cleaned_data['file']

			# nastaveni mailu
			request.user.email = email
			request.user.save()
			msg = "Settings changed."
			state = True

			# avatar
			try:
				#kontrola velikosti
				if(request.FILES['file'].size > MAX_AVATAR_SIZE):
					msg = "Avatar image is too large. Maximum size is " + MAX_AVATAR_SIZE + " bytes."
					state = False
				else:
					filename = "user_"+request.user.username + ".jpg"
					filename_tmp = "tmp_" + request.user.username + "_" + request.FILES['file'].name
					handle_uploaded_file(
						request.FILES['file'],
						filename,
						filename_tmp)
					avatar=Photo(name=request.user.username,gallery=get_avatars_gallery(),path=ITSconf.VTA_data_root+"avatars/"+filename)
					avatar.save()
					profile = UserProfile.objects.get(user=request.user.id)
					profile.avatar = avatar.id
					profile.save()
					msg = "Settings changed."
					state = True
			except:
				pass

			# nastaveni hesla
			if state and (current_password!="" or new_password!="" or new_password_confirm!=""):
				check_current = check_password(current_password, request.user.password)
				if check_current:
					if new_password!="":
						if new_password==new_password_confirm:
							request.user.set_password(new_password)
							request.user.save()
							msg = "Settings changed."
							state = True
						else:
							msg = "New password confirmation failed!"
							state = False
					else:
						msg = "New password cannot be empty!"
						state = False
				else:
					msg = "Current password doesn't match!"
					state = False
		else:
			msg = "Validation error."
			state = False

		profile = UserProfile.objects.get(user=request.user.id)
		avatar = base64.b16encode('media/avatars/' + profile.avatar)
		return render(request, 'itsapp/settings.html', {
			'form': form,
			'msg': msg,
			'state': state,
			'avatar': avatar
		})
	else:
		if(request.user.is_authenticated()):
			form = SettingsForm(initial={'email': request.user.email})

			try:
				profile = UserProfile.objects.get(user=request.user.id)
				avatar = base64.b16encode('media/avatars/' + profile.avatar)
			except:
				avatar = ""
			return render(request, 'itsapp/settings.html', {
				'form': form,
				'avatar': avatar
			})
		else:
			return render(request, 'itsapp/settings.html', {})


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


class SettingsForm(forms.Form):
	email = forms.EmailField( label="E-mail" )
	file = forms.FileField( label="Avatar", required=False )
	current_password = forms.CharField( widget=forms.PasswordInput, label="Current password", required=False )
	new_password = forms.CharField( widget=forms.PasswordInput, label="New password", required=False )
	new_password_confirm = forms.CharField( widget=forms.PasswordInput, label="New password confirmation", required=False )
	
