from django.http import HttpResponseRedirect
from django.views.generic import *
from django.contrib.auth.decorators import login_required
#from django.contrib.auth.models import User
from django.contrib.auth import get_user_model # as per https://docs.djangoproject.com/en/dev/topics/auth/customizing/#referencing-the-user-model
from settings.settings import LANGUAGES
from registration.signals import user_registered

from id.models import Profile, AccountRequest
from id.forms import ProfileUpdateForm, ProfileBasicsForm, ProfileDetailsForm, ProfileAdminForm


class ProfileSetLanguage(TemplateView):
    template_name = 'registration/profile.jinja'

    def get(self, request, lang, **kwargs):
        if lang in [x[0] for x in LANGUAGES]:
            request.session['django_language'] = lang
            if request.user.is_authenticated():
                request.user.locale = lang
                request.user.save()
        return HttpResponseRedirect(request.META["HTTP_REFERER"])


class ProfileUpdate(UpdateView):
    template_name = 'registration/profile.jinja'
    form_class = ProfileUpdateForm
    success_url = "/accounts/profile/"

    def get_object(self, *args, **kwargs):
        if kwargs.has_key("pk"):
            return get_user_model().objects.get(id=kwargs["pk"])
        elif kwargs.has_key("email"):
            return get_user_model().objects.get(email=kwargs["email"])
        return self.request.user

    def get_context_data(self, form):
        obj = self.get_object()
        ctx = super(ProfileUpdate, self).get_context_data()
        ctx = {
            "editing_self": obj == self.request.user
        }
        print "Request method: ", self.request.method
        if self.request.method == "POST":
            ctx["form"] = ProfileUpdateForm(self.request.POST, instance=obj)
            if ctx["form"].is_valid():
                print "Saving form. Form: ", ctx["form"]
                obj = ctx["form"].save()
            else:
                print ctx["form"].errors
            ctx["form_basics"] = ProfileBasicsForm(self.request.POST, instance=obj)
            ctx["form_details"] = ProfileDetailsForm(self.request.POST, instance=obj)
            if obj.is_superuser:
                ctx["form_admin"] = ProfileAdminForm(self.request.POST, instance=obj)
        else:
            ctx["form"] = ProfileUpdateForm(instance=obj)
            ctx["form_basics"] = ProfileBasicsForm(instance=obj)
            ctx["form_details"] = ProfileDetailsForm(instance=obj)
            if obj.is_superuser:
                ctx["form_admin"] = ProfileAdminForm(instance=obj)
        return ctx

class UserList(ListView):
    model = get_user_model()
    paginate_by = 50
    template_name = 'auth/user_list.jinja'

class AccountRequestHome(TemplateView):
    template_name = 'request_account_home.jinja'

    def message(self, where, message):
        self.add_message(message)
        self.redirect_to(where)
        return True

    def fallback_response(self):
        if not self.user:
            return False
        if self.is_user:
            return self.message(
                'request_list',
                'You have already been approved as an Information Requester.')
        if self.is_volunteer:
            return self.message(
                'request_list',
                'You have already been approved as a Volunteer.')
        if models.AccountRequest.pending_for(self.user):
            return self.message(
                'home',
                'You already have a request for an account pending.'
                ' Please be patient.')

class AccountRequestList(ListView):
    template_name = 'id/accountrequest_list.jinja'
    model = AccountRequest

class AccountRequest(AccountRequestHome):
    # form_class = forms.modelform_factory(forms.AccountRequestForm)
    template_name = 'request_account.jinja'

    @login_required
    def _get(self):
        if self.fallback_response():
            return
        form = self.form_class(email=self.email)
        return (self.fallback_response()
                or self.render_response(self.template_name, form=form))

    @login_required
    def _post(self):
        f = self.form_class(self.request.POST)
        f.email.data = self.email

        if not f.validate():
            logging.info("Fail to validate for unknown reason!")
            return self.render_response(self.template_name, form=f)

        account_request = f.save(parent=ndb.Key('Entity', 'accountrequest'),
                                 commit=False)
        account_request.user_profile = self.key
        account_request.put()
        account_request.notify_received()
        self.add_message(_('Request submitted. Our staff will evaluate and '
                           'respond to your request.'), 'success')
        self.redirect_to('home')


class AccountVolunteer(AccountRequest):
    # form_class = forms.modelform_factory(forms.AccountVolunteerForm)
    template_name = 'accountrequest/volunteer_account.jinja'


@@ -1169,36 +1169,138 @@
 self
-, *args, **kwargs):%0A
+):%0A        print %22GET OBJECT: %22 %25 self.kwargs%0A        if self.request.user.is_staff or self.request.user.is_superuser:%0A   
         
 if k
@@ -1295,19 +1295,25 @@
         
+ 
 if 
+self.
 kwargs.h
@@ -1322,24 +1322,28 @@
 _key(%22pk%22):%0A
+    
             
@@ -1381,16 +1381,21 @@
 .get(id=
+self.
 kwargs%5B%22
@@ -1412,13 +1412,22 @@
     
+    
 elif 
+self.
 kwar
@@ -1451,32 +1451,36 @@
 %22):%0A            
+    
 return get_user_
@@ -1505,16 +1505,21 @@
 t(email=
+self.
 kwargs%5B%22
@@ -1774,62 +1774,8 @@
   %7D%0A
-        print %22Request method: %22, self.request.method%0A
     
@@ -1932,65 +1932,8 @@
 ():%0A
-                print %22Saving form. Form: %22, ctx%5B%22form%22%5D%0A
     
@@ -2205,35 +2205,49 @@
 %0A            if 
-obj
+self.request.user
 .is_superuser:%0A 
@@ -2550,19 +2550,33 @@
      if 
-obj
+self.request.user
 .is_supe

Fix viewing other user's account details