#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2002, 2003 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Eric3 Unittest

This is the main Python script that performs the neccessary initialization
of the unittest module and starts the Qt event loop. This is a standalone 
version of the integrated unittest module.
"""

import sys
import os
from qt import QApplication, QTranslator, QTextCodec

import Preferences


def loadTranslator(dirs, tn):
    """
    Global function to find and load a specific translation.

    Arguments
    
        dirs -- searchpath for the translations (list of strings)
        
        tn -- the translation to be loaded (string)
        
    Returns
    
        tuple of a status flag and the loaded translator (int, QTranslator)
    """
    trans = QTranslator(None)
    for dir in dirs:
        loaded = trans.load(tn, dir)
        if loaded:
            return (trans, 1)
            
    print "qtunittest: no translation file '" + tn + "'found."
    print "Using default."
    return (None, 0)

if __name__ == "__main__":
    ericDir = os.path.dirname(sys.argv[0])
    if ericDir == '':
        ericDir = '.'
    app = QApplication(sys.argv)

    # We can only import these after creating the QApplication because they
    # make Qt calls that need the QApplication to exist.
    from PyUnit.UnittestDialog import UnittestDialog
    
    # Set the applications string encoding
    try:
        sys.setappdefaultencoding(str(Preferences.getSystem("StringEncoding")))
    except:
        pass
        
    try:
        fn = sys.argv[1]
    except:
        fn = None
        
    # get the Qt installation directory
    qtdir = Preferences.getQtDir()
    if qtdir is not None:
        if Preferences.getQt("ExportQtDir"):
            os.environ["QTDIR"] = qtdir
    
    # Load translation files and install them
    loaded = 0
    loc = Preferences.getUILanguage()
    if loc is not None:
        if loc == "System":
            loc = str(QTextCodec.locale())
            
        if loc != "C":
            # setup the searchpath for qt
            dirs = [ericDir, "."]
            if qtdir is not None:
                dirs.insert(-1, os.path.join(qtdir, "translations"))
                
            # 1) load translations for qt
            qtTrans, ok = loadTranslator(dirs, "qt_" + loc)
            if ok:
                app.installTranslator(qtTrans)
                
            # 2) load translations for qtunittest
            dirs = [".", ericDir]
            ericTrans, ok = loadTranslator(dirs, "eric3_" + loc)
            if ok:
                app.installTranslator(ericTrans)
            else:
                print "Please report to <eric-bugs@die-offenbachs.de>."
        
    w = UnittestDialog(fn)
    app.setMainWidget(w)
    w.show()
    
    app.exec_loop()
