package dbxml.xqlint;

import java.io.IOException;

import org.w3c.dom.Document;

import de.gmd.ipsi.xql.*;
import de.gmd.ipsi.domutil.*;

import dbxml.sax.*;
import dbxml.dom.JDBCDOMParser;
import dbxml.util.IOUtils;

/**
 * A XQL shell for demonstrating integration of JDBCDOMParser
 * with XQL processor.
 * It uses the XQL parser from GMD-IPSI.
 *  
 * @author Ramnivas Laddad
 */
public class JDBCXQLProcessor {
    /**
     * Create a XQL shell for given DOM document object.
     * Creats shell that prompt user for a query and then prints the result
     * of that query. The shell exits when user types "quit".
     * This method works with any DOM document -- not just that created
     * by the JDBCDOMParser
     *
     * @param document a DOM document object
     */
    public static void processQueries(Document document) {
	System.out.println("XQL-Database shell: "
			   + "Type * to see the full document, quit to exit");
	try {
	    XMLWriter out = new XMLWriter(System.out, "ISO-8859-1");
	    while (true) {
		try {
		    String command = IOUtils.readInput("XQL Query>> ");
		    if (command.equals("quit")) {
			break;
		    } else if (command == null || command.length() == 0) {
			continue;
		    }
		    XQL.execute(command, document, out);
		} catch (XQLException ex1) {
		    System.out.println("Invalid query");
		    continue;
		}
	    }
	} catch (IOException ex2) {
	}		
    }

    /**
     * The main method that creates a DOM document for information in
     * its argument and starts a XQL shell with it.
     *
     * @param argv argument to the program. The valid argument is name
     *             of property file describing the JDBC input source.
     */
    public static void main(String[] argv) {
	if (argv.length != 1) {
	    System.out.println("Usage: java "
			       + "dbxml.xqlint.JDBCXQLProcessor dbPropFile");
	    System.exit(-1);
	}

	Document document = null;
	try {
	    JDBCInputSource inputSource 
		= JDBCSAXUtil.setupSourceFromProperties(argv[0]);
	    document = JDBCDOMParser.createDocument(inputSource);
	} catch (Exception ex) {
	    System.out.println("Failed to create database source");
	    System.exit(-1);
	}
	processQueries(document);
    }
}