package com.sleepycat.dbxml.examples.gettingStarted;

import java.io.*;
import com.sleepycat.dbxml.examples.gettingStarted.myDbEnv;
import com.sleepycat.dbxml.examples.gettingStarted.myXmlContainer;
import com.sleepycat.dbxml.examples.gettingStarted.mdConst;


import com.sleepycat.dbxml.*;
import com.sleepycat.db.*;

class queryForMetaData
{
    
    private static String theContainer = "namespaceExampleData.dbxml";
    private static void usage()
    {
         String usageMessage = "\nThis program retrieves DBXML documents and then retrieves the date and time\n";
                usageMessage += "that the document was stored in the container. You should run exampleLoadContainer\n";
                usageMessage += "before running this example. You are only required to pass this command the path\n";
                usageMessage += "location of the database environment that you specified when you loaded the examples\n";
                usageMessage += "data:\n\n";

                usageMessage += "\t-h <dbenv directory>\n";

                usageMessage += "For example:\n";
                usageMessage += "\tjava com.sleepycat.dbxml.examples.gettingStarted.queryForMetaData -h examplesEnvironment\n";

         System.out.println(usageMessage);
         System.exit( -1 );
    }

    //Shows a timestamp for each record that matches the given XPath query. The timestamp is stored
    // as metadata on each document. This metadata was added to the document when the example data was
    // loaded into the container using exampleLoadContainer.java. The timestamp represents the time
    // when the document was loaded into the container.
    private static void showTimeStamp( XmlContainer container, String XPath, XmlQueryContext context ) throws Throwable
    {
       //Perform a single query against the referenced container using
       // the referenced context. The timestamp metadata attribute is then
       // displayed.
       System.out.println("Exercising query: '" + XPath + "'.");
       System.out.println("Return to continue: ");
       System.in.read();

       //Perform the query
       XmlResults results = container.queryWithXPath(null, XPath, context, 0);
       //We're going to iterate over the results with an XmlDocument
       XmlDocument document = new XmlDocument();
       while (results.next(document)) {
               //We return the metadata as an XmlValue
               XmlValue metaValue = new XmlValue();
               //retrieve the metadata using the uri and name stored in the
               // mdConst utility class. This uri and name are the same values
               // used when the metadata was stored on the document.
               document.getMetaData(mdConst.uri, mdConst.name, metaValue );
               System.out.println("Document " + document.getName() + " stored on " + metaValue.asString(null));
       }
       System.out.println(results.size() + " results returned for query '" + XPath + "'.");
    }


    public static void main(String args[]) throws Throwable
    {

       File path2DbEnv = null;

       for(int i = 0; i < args.length; ++i) {
            if (args[i].startsWith("-")) {
               switch(args[i].charAt(1)) {
                    case 'h':
                         path2DbEnv = new File( args[++i] );
                         break;
                    default:
                    usage();
               }
            } 
       }


       if (path2DbEnv == null || ! path2DbEnv.isDirectory()) {
            usage();
       }


       myDbEnv theDBEnv = null;
       myXmlContainer openedContainer = null;
       try
       {
            //Open the database environment
            theDBEnv = new myDbEnv(path2DbEnv);
            //Open a container in the database environment
            openedContainer = new myXmlContainer(theContainer, theDBEnv);

            //Create a context and declare the namespaces
            XmlQueryContext context = new XmlQueryContext(XmlQueryContext.ResultDocuments, XmlQueryContext.Eager);
            context.setNamespace("fruits", "http://groceryItem.dbxml/fruits");
            context.setNamespace("vegetables", "http://groceryItem.dbxml/vegetables");
            context.setNamespace("desserts", "http://groceryItem.dbxml/desserts");

            //Show all the vegetables
            showTimeStamp(openedContainer.getContainer(), "/vegetables:item", context);

       } catch (Exception e) {

            System.err.println("Error performing query against " + theContainer );
            System.err.println("   Message: " + e.getMessage() );
            throw e;

       } finally {
            if (openedContainer != null) {
               openedContainer.cleanup();
            }

            if (theDBEnv != null) {
               theDBEnv.cleanup();
            }
       }
    } //End main

}
