from __future__ import print_function, unicode_literals

from datetime import datetime
import os

from babel.dates import format_timedelta
import babel.messages.pofile

def to_age(dt, loc):
    return format_timedelta(datetime.now().replace(tzinfo=dt.tzinfo) - dt, locale=loc)

def load_langs(localeDir):
    langs = {}
    for file in os.listdir(localeDir):
        parts = file.split(".")
        if len(parts) == 2 and parts[1] == "po":
            lang = parts[0]
            with open(os.path.join(localeDir, file)) as f:
                catalog = babel.messages.pofile.read_po(f)
                catalog_dict = {}
                for message in catalog:
                    if message.id:
                        catalog_dict[message.id] = message.string
                langs[lang] = catalog_dict
    return langs

LANGS = load_langs("i18n")

def parse_locales(request):
    accept_lang = request.headers.get("Accept-Language", "")
    locales = []
    for lang in accept_lang.split(","):
        lang_parts = lang.split(";")
        locales.append(lang_parts[0])
    return locales

def parse_locale(request):
    for loc in parse_locales(request):
        if loc.startswith("en") or LANGS.has_key(loc):
            return loc
    return "en"

def _(s, loc):
    if not LANGS.has_key(loc):
        return s
    return LANGS[loc].get(s, s)

@@ -162,16 +162,17 @@
 pofile%0A%0A
+%0A
 def to_a
@@ -272,16 +272,17 @@
 e=loc)%0A%0A
+%0A
 def load
@@ -817,16 +817,17 @@
  langs%0A%0A
+%0A
 LANGS = 
@@ -846,16 +846,17 @@
 i18n%22)%0A%0A
+%0A
 def pars
@@ -855,33 +855,32 @@
 def parse_locale
-s
 (request):%0A    a
@@ -944,23 +944,41 @@
    l
-ocales = %5B%5D%0A   
+anguages = (lang.split(%22;%22, 1)%5B0%5D
  for
@@ -1012,169 +1012,34 @@
 %22,%22)
-:%0A        lang_parts = lang.split(%22;%22)%0A        locales.append(lang_parts%5B0%5D)%0A    return locales%0A%0Adef parse_locale(request):%0A    for loc in parse_locales(request)
+)%0A    for loc in languages
 :%0A  
@@ -1131,16 +1131,17 @@
 n %22en%22%0A%0A
+%0A
 def _(s,
@@ -1151,56 +1151,8 @@
 c):%0A
-    if not LANGS.has_key(loc):%0A        return s%0A
     
@@ -1178,9 +1178,32 @@
 et(s, s)
+ if loc in LANGS else s
 %0A

refactor some functions