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

# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os,sys,gettext

def __findFileMO(domain, localedir=None, languages=None, all=0):
    """Модифицированный метод, ищет файл перевода

    замена gettext.find"""
    if localedir is None:
        localedir = gettext._default_localedir
    if languages is None:
        languages = []
        for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
            val = os.environ.get(envar)
            if val:
                languages = val.split(':')
                break
        if 'C' not in languages:
            languages.append('C')
    # now normalize and expand the languages
    nelangs = []
    for lang in languages:
        for nelang in gettext._expand_lang(lang):
            if nelang not in nelangs:
                nelangs.append(nelang)
    # select a language
    if all:
        result = []
    else:
        result = None
    for lang in nelangs:
        if lang == 'C':
            break
        mofile = os.path.join(localedir, '%s_%s.mo' % (domain,lang))
        if os.path.exists(mofile):
            if all:
                result.append(mofile)
            else:
                return mofile
    return result

def exit(codeExit):
    """Метод выхода из программы"""
    sys.exit(codeExit)

def printERROR(errMessage):
    """Вывод ошибки"""
    if errMessage or errMessage=="":
        if type(errMessage)!=str:
            errMessage = str(errMessage)
        errMessage += "\n"
        sys.stderr.write(errMessage)
        try:
            sys.stderr.flush()
        except:
            exit(1)

def printSUCCESS(message,printBR=True):
    """Вывод сообщения о успехе"""
    if message or message=="":
        if type(message)!=str:
            message = str(message)
        if printBR:
            message += "\n"
        sys.stdout.write(message)
        try:
            sys.stdout.flush()
        except IOError:
            exit(1)
