# -*- coding: utf-8 -*-

import json

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import HttpResponseForbidden, HttpResponseRedirect
from django.utils.translation import ugettext as _


class PasswordExpiryMiddleware:
    """Check the password expiration of current user."""

    def process_request(self, request):
        """
        Enforce the password security policy.

        Each time a request is made, we check that the logged-in user's
        password is still valid, and if not, we redirect them to the password
        change form, for immediate action.

        The only alternative for the user is then to go to the logout page,
        which is not affected by the restriction.
        """

        user = request.user
        url = request.path

        # These routes may not exist if we use another ROOT_URLCONF, for example during tests
        # If not exists, we don't need to check the password expiration of the current user.
        try:
            logout_url = reverse('logout')
            password_change_url = reverse('accounts:password_change')
        except NoReverseMatch:
            return

        if (settings.PASSWORD_EXTRA_SECURITY
                and url != logout_url
                and url != password_change_url
                and user.is_authenticated()
                and not user.is_anonymous()):

            if request.user.check_password_expiry():
                messages.error(request, _(
                    u"Your password has expired. Please choose a new one now."
                ))
                return HttpResponseRedirect(password_change_url)


class NonDeletedOrDeactivatedUserMiddleware(object):
    """A middleware to check a user is not deleted or deactivated before proceeding"""

    def process_request(self, request):
        """Enforce the non deleted or deactived user policy

        Parameters
        ----------
        request: HttpRequest
            The request to process

        Returns
        -------
        HttpResponse or None:
            A redirect when HTML mode or a JSON when XHR mode if the user is deleted,
            else None

        """

        try:
            logout_url = reverse('logout')
            if request.path == logout_url:
                return
        except NoReverseMatch:
            pass

        user = request.user

        if user and not user.is_anonymous() and (user.is_deleted or not user.is_active):
            # let's make sure the guy is deconnected
            if user.is_authenticated():
                logout(request)

            # and tell the front what happened
            if request.is_ajax() or 'application/json' in request.META.get('HTTP_ACCEPT', ''):
                return HttpResponseForbidden(json.dumps({
                    'detail': 'MTP_USER_DEACTIVATED'
                }))
            else:
                messages.error(
                    request,
                    _('Your account has been deactivated.')
                )
                return HttpResponseRedirect(settings.LOGIN_URL)
