# -*- coding: utf-8 -*-
import logging, mv_common
import os, re
config_file = "mv_config"

lan_map = {'bg':'bg_BG',
           'cs':'cs_CZ',
           'da':'da_DK',
           'de':'de_DE',
           'el':'el_GR',
           'en_ca':'en_CA',
           'en_ca':'en_CA',
           'en_gb':'en_US',
           'en_GB':'en_US',
           'en_us':'en_US',
           'es_es':'es_ES',
           'es':'es_ES',
           'et':'et_EE',
           'fi':'fi_FI',
           'fr':'fr_FR',
           'he':'he_IL',
           'hr':'hr_HR',
           'hu':'hu_HU',
           'it':'it_IT',
           'ja':'ja_JP',
           'nb':'nb_NO',
           'nl':'nl_NL',
           'pl':'pl_PL',
           'pt_br':'pt_BR',
           'pt':'pt_PT',
           'ru':'ru_RU',
           'sv':'sv_SE',
           'zh_cn':'zh_CN',
           'zh_hk':'zh_HK' }


def genlocale(locale_list):
    logging.info("    Generating locales")
    localefile="/etc/locale.gen"
    f = open(localefile)
    lines = f.readlines()
    f.close()

    f = open(localefile,'w')

    for line in lines:
        outline = line
        for locale in locale_list:
            #print locale, line
            if locale in line:
                outline = line.replace('#','')
            f.write(outline)
    f.close()
    cmd = "/usr/sbin/locale-gen"
    mv_common.runcmd(cmd)


def update_locale_conf(locale):
    logging.info("    Updating /etc/locale.conf")
    line='''LANG="%s"''' %locale
    try:
        f = open('/etc/locale.conf',"w")
        f.write(line)
        f.write("\n")
        f.close()
    except:
        logging.debug("*   couldn't update /etc/locale.conf")


def setup_locale(systemconfig):
    logging.info("____Start of locale/lang config ____")

    if  mv_common.read_config(mv_common.module_config,"lang")  == False  :
        logging.info("____Skipping of lang, config disabled____")
        return

    try:
        language = systemconfig.get("language").lower()
    except:
        language = "en_us"

    try:
        locale = lan_map[language]+".UTF-8"
    except:
        locale = "en_US.UTF-8"
    logging.info("    locale is: %s" %locale)

    genlocale([locale])
    update_locale_conf(locale)

