/*************************************************************************
 *
 *  $RCSfile: XMLDefaultGenerator.java,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dg $ $Date: 2002-05-06 18:37:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
package org.openoffice.configuration;

import org.xml.sax.*;
import org.w3c.dom.*;
import com.sun.xml.tree.XmlDocument;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import com.sun.xml.tree.*;
import java.util.*;
import java.io.*;
import com.jclark.xsl.sax.Driver;

/**
 * Title:        XMLDefaultGenerator<p>
 * Description:  Tool for generating configuration default data<p>
 */
public class XMLDefaultGenerator {

    public  static final String FILE_EXT = ".xml";

    protected String packageName = null;
    protected String componentName = null;
    protected String categoryName = null;
    protected String transformationFile = null;

    /**
     * construct the generator by validation of the source file
     */
    public XMLDefaultGenerator(String sourceFile) throws Exception
    {
        // set the driver for xt
        System.setProperty("com.jclark.xsl.sax.parser", "com.sun.xml.parser.Parser");
        evaluateSchema(sourceFile);
    }

    public String getComponentName() {return componentName;}
    public String getPackageName() {return packageName;}
    public String getCategoryName() {return categoryName;}

    /**
     * construct the generator by validation of the source file
     */
    protected void evaluateSchema(String schemaFile) throws Exception
    {
        try
        {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // factory.setValidating(true);

            // Parse the input
            SAXParser saxParser = factory.newSAXParser();
            Inspector inspector = new Inspector();
            saxParser.parse( new File(new File(schemaFile).getAbsolutePath()).toURL().toString(), inspector );

            // get the necessary information for generation
            packageName = inspector.packageName;
            componentName = inspector.componentName;
            categoryName = inspector.categoryName;
            transformationFile = inspector.transformationFile;
        }
        catch (SAXParseException spe) {
           // Error generated by the parser
           System.out.println ("\n** Parsing error"
              + ", line " + spe.getLineNumber ()
              + ", uri " + spe.getSystemId ());
           System.out.println("   " + spe.getMessage() );
           throw spe;
        }
        catch (SAXException sxe) {
           // Error generated by this application
           // (or a parser-initialization error)
           Exception  x = sxe;
           if (sxe.getException() != null)
               x = sxe.getException();
           x.printStackTrace();
           throw sxe;
        }
        catch (IOException ioe) {
           // I/O error
           ioe.printStackTrace();
           throw ioe;
        }
        catch (Exception pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
            throw pce;
        }
    }

    /**
     *  creating the destination file name
     */
    public String getTargetName(String aRoot, String aKind) throws Exception
    {
        String aRelPath = packageName.replace('.', File.separatorChar);

        // create the instance directory
        File aFile = new File(aRoot + File.separatorChar + aKind + File.separatorChar +
            aRelPath + File.separatorChar + componentName + FILE_EXT);

        return aFile.getPath();
    }

    /**
     *  generating the target document
     */
    public void generate(String argv [], boolean asTemplate) throws Exception
    {
        // add the necessary transformation parameters
        {
            String[] args = new String[argv.length + 1];
            for (int i = 0; i < argv.length; i++)
                args[i] = argv[i];

            args[1] = argv[1] + File.separator + transformationFile;

            // handle the path parameter for the source
            args[3] = "path=" + Generator.getAbsolutePath(argv[3]);
            args[argv.length] = "pathSeparator=" + File.pathSeparator;
            argv = args;
        }

        try
        {
            // make sure that all directories exist
            File path = new File(argv[2]).getParentFile();
            path.mkdirs();

            String[] args = null;
            // templates need a new argument, which is used for
            // as parameter for the xsl translation
            if (asTemplate)
            {
                args = new String[argv.length + 1];
                for (int i = 0; i < argv.length; i++)
                    args[i] = argv[i];

                args[argv.length] = "templates=true";
            }
            else
                args = argv;

            Driver.main(args);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *  generating the instance document
     */
    protected void generateInstanceFile(String argv []) throws Exception
    {
        argv[2] = getTargetName(argv[2], "instance");
        generate(argv, false);
    }

    /**
     *  generating the template document
     */
    protected void generateTemplateFile(String argv []) throws Exception
    {
        argv[2] = getTargetName(argv[2], "template");
        generate(argv, true);
    }

    public static void main (String argv [])
    {
        if (argv.length < 4) {
            System.err.println ("Usage: cmd <filename> <xsldir> <outdir> <include-path> [transformation parameters]");
            System.err.println ("<filename>: Configuration description file");
            System.err.println ("<xsldir>: Directory where to locate the transformation files used");
            System.err.println ("<outdir>: Directory where to generate the output files");
            System.err.println ("<include-path>: Path where to find imported configuration files");
            System.exit (1);
        }

        try
        {
            XMLDefaultGenerator generator = new XMLDefaultGenerator(argv [0]);

            String[] args = new String[argv.length + 1];
            for (int i = 0; i < argv.length; i++)
                args[i] = argv[i];

            String url = new File(argv[2] + File.separator + "template")
                .getAbsoluteFile().toURL().toString();
            args[argv.length] = "templateURL=" + url;

            // create the instance file
            generator.generateInstanceFile((String[])args.clone());

            // create the template file
            generator.generateTemplateFile((String[])args.clone());
        }
        catch (Exception pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
            System.exit (1);
        }
    }
}
