# -*- coding: utf-8 -*-
import json

from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView, UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.template import RequestContext
from django.contrib.auth.models import User

from accounts.forms import SignupForm, AddUserMultiForm, UserUpdateForm, ProfileUpdateForm
from accounts.models import UserProfile
from core.views import AdminRequiredMixin

# Create your views here.
OTHER_KEY = ['id', 'school', 'users', 'user', 'user_id']
LOGIN_ERROR_MSG = 'incorrect id or password'
METHOD_MISMATCH = 'request method mismatch'
NOT_LOGIN_MSG = '로그인 해 주세요'
NOT_ADMIN = '권한이 없습니다.'


# User 확장전의 create뷰 지금은 쓰이지 않는다
class UserCreateView(CreateView):
	template_name = 'accounts/register.html'
	form_class = SignupForm
	success_url = reverse_lazy('accounts:custom_admin_list')


# 확장후의 multi form create view
class AddUserView(AdminRequiredMixin, CreateView):
	form_class = AddUserMultiForm
	template_name = "accounts/register.html"
	success_url = reverse_lazy('accounts:custom_admin_list')
	
	def get_context_data(self, **kwargs):
		context = super(AddUserView, self).get_context_data(**kwargs)
		context['selectedCategory'] = 'user'
		context['selectedSubCategory'] = 'user'
		return context

	def form_valid(self, form):
		user_form = form['user'].save()
		user = User.objects.get(username=user_form.username)
		profile_form = form['profile'].save(commit=False)
		profile = UserProfile.objects.get(user=user)
		profile.mobile = profile_form.mobile
		profile.company = profile_form.company
		profile.save()
		return redirect(self.success_url)


class UserCreateDoneTV(TemplateView):
	template_name = 'accounts/login.html'

	def get_context_data(self, **kwargs):
		context = super(UserCreateDoneTV, self).get_context_data(**kwargs)
		context['create'] = True
		return context


class UserPasswordChangeDoneTV(TemplateView):
	template_name = 'accounts/login.html'

	def get_context_data(self, **kwargs):
		context = super(UserPasswordChangeDoneTV, self).get_context_data(**kwargs)
		context['password_change'] = True
		return context


@csrf_exempt
def loginAjax(request):
	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']

		# if username or password is null
		# this case have verified on front page.
		if not request.POST['username'] or not request.POST['password']:
			response = {'success':False, 'reason':'InvalidIdPasswd'}
			return HttpResponse(json.dump(response))
		try:
			user = authenticate(username=username, password=password)
			if user is not None:
				if user.is_active:
					login(request, user)
					#request.session['user'] = request.user
					#request.session['userinformation'] = request.user.userinformation
					#request.session.set_expiry(timedelta(days=365))
					variables = {'success': True, 'id': user.id, 'permission': 1}
					return HttpResponse(json.dumps(variables), content_type='application/json')
				else:
					response = {'error':LOGIN_ERROR_MSG}
					return render_to_response('pages/errorPage.html', RequestContext(request, response))
			else:
				variables = {'success':False, 'reason':'InvalidIdPasswd'}
				return render_to_response('pages/errorPage.html', RequestContext(request, variables))
		except:
			raise Http404


@csrf_exempt
def passwdCheck(request):
	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']

		if not request.POST['username'] or not request.POST['password']:
			response = {'success':False, 'reason':'InvalidIdPasswd'}
			return HttpResponse(json.dump(response))
		user = authenticate(username=username, password=password)
		if user is not None:
			if user.is_active:
				login(request, user)
				return HttpResponse(json.dumps({'success': True}), content_type='application/json')
			else:
				return HttpResponse(json.dumps({'success': False}), content_type='application/json')
		else:
			return HttpResponse(json.dumps({'success': False}), content_type='application/json')


class UserUpdateView(UpdateView):
	template_name = 'accounts/user_update.html'
	form_class = UserUpdateForm

	def get_object(self, queryset=None):
		return self.request.user

	def get_context_data(self, **kwargs):
		context = super(UserUpdateView, self).get_context_data(**kwargs)
		if self.request.POST:
			context['formset'] = ProfileUpdateForm(self.request.POST, instance=self.object.userprofile)
		else:
			context['formset'] = ProfileUpdateForm(instance=self.object.userprofile)
		print context
		return context

	def form_valid(self, form):
		context = self.get_context_data()
		formset = context['formset']
		if formset.is_valid():
			self.object = form.save()
			formset.instance = self.object.userprofile
			formset.save()
			return redirect('home')
		else:
			return self.render_to_response(self.get_context_data(form=form))