# Path: kraut_accounts/models.py
# class UserExtension(models.Model):
#     user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
#     icon = models.CharField(max_length=100, default="ns_icon/octalpus.png")
#     namespaces = models.ManyToManyField(Namespace, blank=True)
# 
# Path: kraut_accounts/forms.py
# class PasswordChangeCustomForm(Form):
#     old_password = CharField(required=True, label="Old Password", widget=PasswordInput(attrs={'class': 'form-control'}))
#     new_password1 = CharField(required=True, label="New Password", widget=PasswordInput(attrs={'class': 'form-control'}))
#     new_password2 = CharField(required=True, label="Repeat New Password", widget=PasswordInput(attrs={'class': 'form-control'}))
# 
# Path: kraut_parser/models.py
# class Namespace(models.Model):
#     namespace = models.CharField(max_length=255, default='nospace', unique=True)
#     description = models.TextField(null=True, blank=True)
# 
#     def __unicode__(self):
#         return u"%s" % (self.namespace)
# 
#     class Meta:
#         ordering = ['namespace']
# 
# Path: kraut_intel/utils.py
# def get_icon_for_namespace(namespace):
#     """ Return the static path to the icon associated with given namespace
#     """
#     try:
#         if namespace.count(':')>0:
#             namespace = namespace.split(':')[0]
#         icon = NamespaceIcon.objects.get(namespace=namespace)
#     except Exception as e:
#         return static('ns_icon/octalpus.png')
#     return static('ns_icon/%s' % (icon.icon))


from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.hashers import check_password
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.template import RequestContext
from django.contrib import messages
from kraut_accounts.models import UserExtension
from kraut_accounts.forms import PasswordChangeCustomForm
from kraut_parser.models import Namespace
from kraut_intel.utils import get_icon_for_namespace



# Create your views here.

def accounts_change_password(request):
    """change password
    """
    if request.method == 'POST':
        form = PasswordChangeCustomForm(request.POST)
        if form.is_valid():
            current_user = request.user
            # check if old password equals current password
            old_pass = form.cleaned_data['old_password']
            n1_pass = form.cleaned_data['new_password1']
            n2_pass = form.cleaned_data['new_password2']
            if not current_user.check_password(old_pass):
                messages.error(request, 'Old password wrong!')
                return HttpResponseRedirect(reverse("accounts:changepw"))
            if n1_pass != n2_pass:
                messages.error(request, 'New password does not match!')
                return HttpResponseRedirect(reverse("accounts:changepw"))
            # change password
            current_user.set_password(n1_pass)
            update_session_auth_hash(request, request.user)
            current_user.save()
            messages.info(request, 'Password successfully changed!')
        else:
            messages.error(request, 'Failure updating password!')
        return HttpResponseRedirect(reverse("accounts:changepw"))

# Path: kraut_accounts/models.py
# class UserExtension(models.Model):
#     user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
#     icon = models.CharField(max_length=100, default="ns_icon/octalpus.png")
#     namespaces = models.ManyToManyField(Namespace, blank=True)
# 
# Path: kraut_accounts/forms.py
# class PasswordChangeCustomForm(Form):
#     old_password = CharField(required=True, label="Old Password", widget=PasswordInput(attrs={'class': 'form-control'}))
#     new_password1 = CharField(required=True, label="New Password", widget=PasswordInput(attrs={'class': 'form-control'}))
#     new_password2 = CharField(required=True, label="Repeat New Password", widget=PasswordInput(attrs={'class': 'form-control'}))
# 
# Path: kraut_parser/models.py
# class Namespace(models.Model):
#     namespace = models.CharField(max_length=255, default='nospace', unique=True)
#     description = models.TextField(null=True, blank=True)
# 
#     def __unicode__(self):
#         return u"%s" % (self.namespace)
# 
#     class Meta:
#         ordering = ['namespace']
# 
# Path: kraut_intel/utils.py
# def get_icon_for_namespace(namespace):
#     """ Return the static path to the icon associated with given namespace
#     """
#     try:
#         if namespace.count(':')>0:
#             namespace = namespace.split(':')[0]
#         icon = NamespaceIcon.objects.get(namespace=namespace)
#     except Exception as e:
#         return static('ns_icon/octalpus.png')
#     return static('ns_icon/%s' % (icon.icon))


# Path: kraut_accounts/views.py
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.hashers import check_password
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.template import RequestContext
from django.contrib import messages
from kraut_accounts.models import UserExtension
from kraut_accounts.forms import PasswordChangeCustomForm
from kraut_parser.models import Namespace
from kraut_intel.utils import get_icon_for_namespace




# Create your views here.

def accounts_change_password(request):
    """change password
    """
    if request.method == 'POST':
        form = PasswordChangeCustomForm(request.POST)
        if form.is_valid():
            current_user = request.user
            # check if old password equals current password
            old_pass = form.cleaned_data['old_password']
            n1_pass = form.cleaned_data['new_password1']
            n2_pass = form.cleaned_data['new_password2']
            if not current_user.check_password(old_pass):
                messages.error(request, 'Old password wrong!')
                return HttpResponseRedirect(reverse("accounts:changepw"))
            if n1_pass != n2_pass:
                messages.error(request, 'New password does not match!')
                return HttpResponseRedirect(reverse("accounts:changepw"))
            # change password
            current_user.set_password(n1_pass)
            update_session_auth_hash(request, request.user)
            current_user.save()
            messages.info(request, 'Password successfully changed!')
        else:
            messages.error(request, 'Failure updating password!')
        return HttpResponseRedirect(reverse("accounts:changepw"))

    context = {'form': PasswordChangeCustomForm()}