import logging

from django.conf import settings
from django.utils import timezone

logger = logging.getLogger(__name__)


class TimezoneMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def __getUserTimeZone(self, request):
        # info = IPResolver(request).getGeoInfo()
        # return pytz.country_timezones[info["country_code"]][0]
        if not request.user.is_anonymous:
            return request.user.profile.timezone

    def process_request(self, request):
        try:
            tz = self.__getUserTimeZone(request) or settings.TIME_ZONE
            timezone.activate(tz)
            logger.info('Time zone "%s" activated' % str(tz))
        except Exception as e:
            logger.error("Unable to set timezone: %s" % str(e))
