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

from __future__ import unicode_literals
import logging

import pytz

from django.contrib.auth import logout
from django.utils import timezone

try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:  # Django < 1.10
    MiddlewareMixin = object

from ..core.conf import settings
from .models import UserProfile


__all__ = [
    'TimezoneMiddleware',
    'LastIPMiddleware',
    'LastSeenMiddleware',
    'ActiveUserMiddleware']

logger = logging.getLogger('django')


class TimezoneMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.user.is_authenticated():
            try:
                timezone.activate(request.user.st.timezone)
            except pytz.exceptions.UnknownTimeZoneError:
                timezone.deactivate()
                logger.error(
                    '%s is not a valid timezone.' %
                    request.user.st.timezone)
        else:
            timezone.deactivate()


class LastIPMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            return

        last_ip = request.META['REMOTE_ADDR'].strip()

        if request.user.st.last_ip == last_ip:
            return

        (UserProfile.objects
            .filter(user__pk=request.user.pk)
            .update(last_ip=last_ip))


class LastSeenMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            return

        threshold = settings.ST_USER_LAST_SEEN_THRESHOLD_MINUTES * 60
        delta = timezone.now() - request.user.st.last_seen

        if delta.seconds < threshold:
            return

        (UserProfile.objects
            .filter(user__pk=request.user.pk)
            .update(last_seen=timezone.now()))


class ActiveUserMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            return

        if not request.user.is_active:
            logout(request)

@@ -600,32 +600,36 @@
 st):%0A        if 
+not 
 request.user.is_
@@ -658,24 +658,70 @@
        t
+imezone.deactivate()%0A            return%0A%0A        t
 ry:%0A
-    
         
@@ -776,20 +776,16 @@
         
-    
 except p
@@ -825,36 +825,32 @@
 or:%0A            
-    
 timezone.deactiv
@@ -867,20 +867,16 @@
         
- 
-   
 logger.e
@@ -881,20 +881,16 @@
 .error(%0A
-    
         
@@ -930,30 +930,9 @@
 ne.'
- %25%0A                   
+,
  req
@@ -958,56 +958,8 @@
 ne)%0A
-        else:%0A            timezone.deactivate()%0A
 %0A%0Acl
@@ -1646,15 +1646,23 @@
 lta.
+total_
 seconds
+()
  %3C t
@@ -1732,38 +1732,32 @@
         .filter(
-user__
 pk=request.user.
@@ -1748,32 +1748,35 @@
 pk=request.user.
+st.
 pk)%0A            

fix last_seen