import os
import pygeoip
from django.conf import settings
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin

class LanguageMiddleware(MiddlewareMixin):
    """Django translation middleware
        * https://github.com/codingforentrepreneurs/Guides/blob/master/all/Django_Translation.md
    """

    def get_client_ip(self, request):
        """
        Get Client IP.
        Refference: http://stackoverflow.com/a/4581997/6396981
        """
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def process_request(self, request):
        geoipdb = os.path.join(settings.BASE_DIR, 'yourproject/geoipdb/GeoIP.dat')
        gi = pygeoip.GeoIP(geoipdb)

        client_ip = self.get_client_ip(request)
        client_country_code = gi.country_code_by_name(client_ip).lower()

        if 'lang' in request.GET:
            translation.activate(request.GET.get('lang'))
        elif client_country_code != 'id' and client_country_code != '':
            translation.activate('en')

"""
#1. settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    ......

    'django.middleware.locale.LocaleMiddleware',
    'yourproject.middleware.LanguageMiddleware',
]

from django.utils.translation import ugettext_lazy as _

LANGUAGE_CODE = 'en'
LANGUAGES = (
    ('en', _('English')),
    ('id', _('Indonesia'))
)
DEFAULT_LANGUAGE = 1
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'yourproject/locale'),
)


#2. urls.py
from django.conf import settings
from django.contrib import admin
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    .....
    .....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)



#3. Templates
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <div class="form-group">
    <select name="language" onchange="javascript:form.submit()">
      <option value="en" {% if request.LANGUAGE_CODE == 'en' %}selected="selected"{% endif %}>English</option>
      <option value="id" {% if request.LANGUAGE_CODE == 'id' %}selected="selected"{% endif %}>Indonesia</option>
    </select>
  </div>
</form>
"""