#!/usr/bin/env python3
import os
import sys

lib_path = os.path.relpath('etmTk/')
sys.path.append(lib_path)

# from etmTk import view
from etmTk.data import setup_logging
import codecs
import yaml
import locale
import gettext
import platform

import logging
import logging.config
logger = logging.getLogger()

log_levels = [str(x) for x in range(1, 6)]

from locale import getpreferredencoding
from sys import stdout

try:
    dterm_encoding = stdout.term_encoding
except AttributeError:
    dterm_encoding = None
if not dterm_encoding:
    dterm_encoding = getpreferredencoding()

term_encoding = dterm_encoding = dfile_encoding = codecs.lookup(dterm_encoding).name

if __name__ == "__main__":
    etmdir = language = use_locale = ''
    loglevel = '3'
    trans = gettext.NullTranslations()
    help = False
    argstr = " ".join(sys.argv)
    etm = sys.argv[0]
    if len(sys.argv) > 1 and sys.argv[1] in log_levels:
        loglevel = sys.argv.pop(1)

    if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
        temp = sys.argv.pop(1)
        logger.debug("got directory: {0}".format(temp))
        oldpath = os.path.join(temp, 'etm.cfg')
        newpath = os.path.join(temp, 'etmtk.cfg')
        if os.path.isfile(newpath) or os.path.isfile(oldpath):
            etmdir = temp

        locale_cfg = os.path.normpath(os.path.join(etmdir, 'locale.cfg'))
        if os.path.isfile(locale_cfg):
            fo = codecs.open(locale_cfg, 'r', dfile_encoding)
            use_locale = yaml.load(fo)
            fo.close()

        if use_locale:
            locale.setlocale(locale.LC_ALL, map(str, use_locale[0]))
            lcl = locale.getlocale()
            lang = use_locale[0][0]
            localedir = os.path.join(etmdir, "languages")
            trans = gettext.translation(lang, localedir=localedir, languages=[lang], fallback=True)
    else:
        lcl = locale.getdefaultlocale()

    uu = (platform.python_version() < '3')
    if uu:
        trans.install(unicode=True)
    else:
        trans.install()

    setup_logging(loglevel, etmdir=etmdir)

    if len(sys.argv) > 1:
        logger.debug("calling data.main with etmdir: {0}, argv: {1}".format(etmdir, sys.argv))
        import etmTk.data as data
        data.main(etmdir, sys.argv)

    else:
        from etmTk import view
        logger.debug("calling view.main with etmdir: {0}".format(etmdir))
        view.main(dir=etmdir)
        sys.exit()
