/**********************************************************************
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
** Copyright (c) 2001 Phil Thompson <phil@river-bank.demon.co.uk>
**
** This file is part of TQt Designer.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include "uic.h"
#include "parser.h"
#include "widgetdatabase.h"
#include "domtool.h"
#include <tqapplication.h>
#include <tqfile.h>
#include <tqstringlist.h>
#include <tqdatetime.h>
#define NO_STATIC_COLORS
#include <globaldefs.h>
#include <tqregexp.h>
#include <stdio.h>
#include <stdlib.h>

int main( int argc, char * argv[] )
{
    PyIndent indent;
    bool testCode = false, execCode = false;
    bool subcl = false;
    bool imagecollection = false;
    TQStringList images;
    const char *error = 0;
    const char* fileName = 0;
    TQCString outputFile;
    const char* projectName = 0;
    const char* trmacro = 0;
    bool fix = false;
    TQApplication app(argc, argv, false);
    TQString className, uicClass;

    for ( int n = 1; n < argc && error == 0; n++ ) {
	TQCString arg = argv[n];
	if ( arg[0] == '-' ) {			// option
	    TQCString opt = &arg[1];
	    if ( opt[0] == 'o' ) {		// output redirection
		if ( opt[1] == '\0' ) {
		    if ( !(n < argc-1) ) {
			error = "Missing output-file name";
			break;
		    }
		    outputFile = argv[++n];
		} else
		    outputFile = &opt[1];
	    } else if ( opt[0] == 'e' || opt == "embed" ) {
		imagecollection = true;
		if ( opt == "embed" || opt[1] == '\0' ) {
		    if ( !(n < argc-1) ) {
			error = "Missing name of project";
			break;
		    }
		    projectName = argv[++n];
		} else
		    projectName = &opt[1];
	    } else if ( opt == "subimpl" ) {
		subcl = true;
		if ( !(n < argc-1) ) {
		    error = "Missing class name";
		    break;
		}
		className = argv[++n];
	    } else if ( opt == "tr" ) {
		if ( opt == "tr" || opt[1] == '\0' ) {
		    if ( !(n < argc-1) ) {
			error = "Missing tr macro";
			break;
		    }
		    trmacro = argv[++n];
		} else {
		    trmacro = &opt[1];
		}
	    } else if ( opt == "version" ) {
		fprintf( stderr,
			 "Python User Interface Compiler %s for TQt version %s\n",
			 PYTQT_VERSION, TQT_VERSION_STR );
		return 1;
	    } else if ( opt == "help" ) {
		break;
	    } else if ( opt == "fix" ) {
		fix = true;
	    } else if ( opt[0] == 'p' ) {
		uint tabstop;
		bool ok;

		if ( opt[1] == '\0' ) {
		    if ( !(n < argc-1) ) {
			error = "Missing Python indent";
			break;
		    }
		    tabstop = TQCString(argv[++n]).toUInt(&ok);
		} else
		    tabstop = opt.mid(1).toUInt(&ok);

		if (ok)
		    indent.setTabStop(tabstop);
		else
		    error = "Invalid Python indent";
	    } else if ( opt == "test" ) {
		testCode = true;
	    } else if ( opt == "x" ) {
		execCode = true;
	    } else {
		error = "Unrecognized option";
	    }
	} else {
	    if ( imagecollection )
		images << argv[n];
	    else if ( fileName )		// can handle only one file
		error	 = "Too many input files specified";
	    else
		fileName = argv[n];
	}
    }

    if ( argc < 2 || error || (!fileName && !imagecollection ) ) {
	fprintf( stderr, "PyTQt user interface compiler.\n" );
	if ( error )
	    fprintf( stderr, "pytquic: %s\n", error );

	fprintf( stderr, "Usage: %s  [options] [mode] <uifile>\n"
		 "\nGenerate implementation:\n"
		 "   %s  [options] <uifile>\n"
		 "Generate image collection:\n"
		 "   %s  [options] -embed <project> <image1> <image2> <image3> ...\n"
		 "\t<project>\tproject name\n"
		 "\t<image[0..n]>\timage files\n"
		 "Generate subclass implementation:\n"
		 "   %s  [options] -subimpl <classname> <uifile>\n"
		 "\t<classname>\tname of the subclass to generate\n"
		 "Options:\n"
		 "\t-o file\t\tWrite output to file rather than stdout\n"
		 "\t-p indent\tSet the Python indent in spaces (0 to use a tab)\n"
		 "\t-tr func\tUse func() rather than TQApplication.translate() for i18n\n"
		 "\t-x\t\tGenerate extra code to test and display the class\n"
		 "\t-test\t\tGenerate extra code to test but not display the class\n"
		 "\t-version\tDisplay version of pytquic\n"
		 "\t-help\t\tDisplay this information\n"
		 , argv[0], argv[0], argv[0], argv[0]);
	return 1;
    }

    Uic::setIndent(indent);

    TQFile fileOut;
    if ( !outputFile.isEmpty() ) {
	fileOut.setName( outputFile );
	if (!fileOut.open( IO_WriteOnly ) )
	    tqFatal( "pytquic: Could not open output file '%s'", outputFile.data() );
    } else {
	fileOut.open( IO_WriteOnly, stdout );
    }
    TQTextStream out( &fileOut );

    if ( imagecollection ) {
	out.setEncoding( TQTextStream::UnicodeUTF8 );
	out << "# -*- coding: latin-1 -*-\n\n";
	Uic::embed( out, projectName, images );
	return 0;
    }


    out.setEncoding( TQTextStream::UnicodeUTF8 );
    TQFile file( fileName );
    if ( !file.open( IO_ReadOnly ) )
	tqFatal( "pytquic: Could not open file '%s' ", fileName );

    TQDomDocument doc;
    TQString errMsg;
    int errLine;
    if ( !doc.setContent( &file, &errMsg, &errLine ) )
	tqFatal( TQString("pytquic: Failed to parse %s: ") + errMsg + TQString (" in line %d\n"), fileName, errLine );

    TQDomElement e = doc.firstChild().toElement();
    if ( e.hasAttribute("version") && e.attribute("version").toDouble() > 3.3 ) {
	tqWarning( TQString("pytquic: File generated with too recent version of TQt Designer (%s vs. %s)"),
		  e.attribute("version").local8Bit().data(), TQT_VERSION_STR );
	return 1;
    }

    DomTool::fixDocument( doc );

    if ( fix ) {
	out << doc.toString();
	return 0;
    }

    out << "# -*- coding: utf-8 -*-\n\n";

    if ( !subcl ) {
	out << "# Form implementation generated from reading ui file '" << fileName << "'" << endl;
	out << "#" << endl;
	out << "# Created by: The PyTQt User Interface Compiler (pytquic) " << PYTQT_VERSION << endl;
	out << "#" << endl;
	out << "# WARNING! All changes made in this file will be lost!" << endl;
	out << endl;
	out << endl;
    }

    if (testCode || execCode)
	out << "import sys" << endl;
 
    out << "from PyTQt.tqt import *" << endl;

    Uic( fileName, outputFile, out, doc, subcl, trmacro, className, uicClass );

    if (testCode || execCode) {
	out << endl;
	out << indent << "if __name__ == \"__main__\":" << endl;
	++indent;
	out << indent << "a = TQApplication(sys.argv)" << endl;
	out << indent << "TQObject.connect(a,TQ_SIGNAL(\"lastWindowClosed()\"),a,TQ_SLOT(\"quit()\"))" << endl;
	out << indent << "w = " << (subcl ? className : uicClass) << "()" << endl;
	out << indent << "a.setMainWidget(w)" << endl;

	if (execCode) {
	    out << indent << "w.show()" << endl;
	    out << indent << "a.exec_loop()" << endl;
	}

	--indent;
    }

    return 0;
}
