#!/usr/bin/python
###########################################################################
# tqtuicompiler - description                                              #
# ------------------------------                                          #
# begin     : Thu Apr 21 2005                                             #
# copyright : (C) 2005 by Simon Edwards                                   #
# email     : simon@simonzone.com                                         #
#                                                                         #
###########################################################################
#                                                                         #
#   This program is free software; you can redistribute it and/or modify  #
#   it under the terms of the GNU Library General Public License as       #
#   published by the Free Software Foundation; either version 2 of the    #
#   License, or (at your option) any later version.                       #
#                                                                         #
###########################################################################

import os
import sys
from PyTQt import pytqtconfig
from distutils.spawn import *
import traceback

pytqt_configuration = pytqtconfig.Configuration()
pytquic_exe = None

############################################################################
def FindPytquic():
    global pytquic_exe
    if pytquic_exe is not None: return pytquic_exe
    
    pytquic_exe = find_executable('pytquic',pytqt_configuration.pytqt_bin_dir)
    if pytquic_exe is None:
        # Search on the $Path.
        pytquic_exe = find_executable('pytquic')

############################################################################
def CompileUI(ui_file_name, py_file_name=None, kde=False):
    pytquic_exe = find_executable('pytquic',pytqt_configuration.default_bin_dir)
    if pytquic_exe is None:
        # Search on the $Path.
        pytquic_exe = find_executable('pytquic')
    if pytquic_exe is None:
        pass  # FIXME raise something!
        
    if py_file_name is None:
        py_file_name = os.path.splitext(os.path.basename(ui_file_name))[0] + '.py'
    
    tmp_file_name = py_file_name + '.bak'
    cmd = [pytquic_exe]
    if kde:
        cmd.append('-tr')
        cmd.append('i18n')
    cmd.append('-o')
    cmd.append(tmp_file_name)
    cmd.append(ui_file_name)
    spawn(cmd)
    
    input = open(tmp_file_name, 'r')
    output = open(py_file_name, 'w')
    for line in input.readlines():
        if kde and string.strip(line) == 'from PyTQt.tqt import *':
            output.write(line)
            output.write('from tdecore import *\nfrom tdeui import *\n\n')
        elif kde and string.find(line, " = KDatePicker(") != -1:
            o = string.find(line, ",")
            output.write(line[:o] + ",TQDate.currentDate()" + line[o:])
        else:
            output.write (line)

    input.close()
    output.close()

    os.remove(tmp_file_name)

############################################################################
def DynamicImport(importargs,kde=False):
    file_name = importargs[0].replace('.',os.sep)
    file_name_ui = file_name + '.ui'
    if os.path.exists(file_name_ui):
        try:
            UpdateUI(file_name_ui,kde)
        except:
            traceback.print_exc()
            raise ImportError("Unable to compile TQt designer file %s." % args[0])

############################################################################
def UpdateUI(ui_file,kde=False):
    py_file = ui_file[:-3] + '.py'
    remake = False
    if os.path.exists(py_file):
        remake = os.stat(py_file).st_mtime <= os.stat(ui_file).st_mtime
    else:
        remake = True

    if remake:
        CompileUI(ui_file, py_file, kde)

############################################################################
def main():
    # FIXME parse args and add --kde parameter.
    if len(sys.argv)!=3:
        print("""\nUsage:
tqtuicompiler filename.ui filename.py\n\n
""")
        return

    CompileUI(sys.argv[1],sys.argv[2])
    
if __name__=='__main__':
    main()
