#include <fstream>
#include <cstdio>

#include "myDbEnv.hpp"
#include "myXmlContainer.hpp"

using namespace DbXml;

void usage()
{
      std::cerr  <<   "This program illustrates how to query for documents that require namespace\n"
                 <<   "usage in the query.  You should pre-load the container using\n"
                 <<   "loadExamplesData.[sh|cmd] before running this example.  You are only required\n"
                 <<   "to pass this command the path location of the database environment that you\n"
                 <<   "specified when you pre-loaded the examples data:\n\n"


                 <<   "\t-h <dbenv directory>" << std::endl;
        exit( -1 );
}

void doContextQuery( const XmlContainer &container, const std::string &XPath, XmlQueryContext &context )
{
    ////////////////////////////////////////////////////////////////////////
    //////  Performs a simple XPath query (with context) against the ///////
    //////  provided container.                                      ///////
    ////////////////////////////////////////////////////////////////////////

    ///// some defensive code eliminated for clarity //

    // Perform the query. Result type is by default Result Document
    
    try {
        std::cout << "Exercising query '" << XPath << "' " << std::endl;
        std::cout << "Return to continue: ";
        getc(stdin);

        XmlResults results( container.queryWithXPath(0, XPath, &context ) );
        XmlValue value;
        while( results.next(value) )
        {
            // Obtain the value as a string and print it to the console
            std::cout << value.asString() << std::endl;
        }

        std::cout << results.size() << " objects returned for expression '" << XPath << "'\n" << std::endl;

    }
    //Catches XmlException
    catch(std::exception &e)
    {
        std::cerr << "Query " << XPath << " failed\n";
        std::cerr << e.what() << "\n";
        exit( -1 );
    }

}

int main(int argc, char **argv)
{

    std::string path2DbEnv;
    std::string theContainer = "namespaceExampleData.dbxml";
    for ( int i=1; i<argc; i++ )
    {
        if ( argv[i][0] == '-' )
        {
            switch(argv[i][1])
            {
              case 'h':
                path2DbEnv = argv[++i];
                break;
              default:
                usage();
            }
         }
     }

     if (! path2DbEnv.length() )
        usage();

    //Open a container in the db environment
    myDbEnv theDBEnv( path2DbEnv ); 
    myXmlContainer openedContainer( theContainer, theDBEnv );

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

    //Set a variable
    context.setVariableValue( "aDessert", "Blueberry Boy Bait");

    //Perform the queries

    //Find all the Vendor documents in the database. Vendor documents do
    // not use namespaces, so this query returns documents.
    doContextQuery( openedContainer.getContainer(), "/vendor", context );

    //Find the product document for "Lemon Grass". This query returns no documents
    // because a namespace prefix is not identified for the 'item' node.
    doContextQuery( openedContainer.getContainer(), "/item/product[text()=\"Lemon Grass\"]", context);

    //Find the product document for "Lemon Grass" using the namespace prefix 'fruits'. This
    // query successfully returns a document.
    doContextQuery( openedContainer.getContainer(), "/fruits:item/product[text()=\"Lemon Grass\"]", context);

    //Find all the vegetables
    doContextQuery( openedContainer.getContainer(), "/vegetables:item", context);

    //Find the  dessert called Blueberry Boy Bait
    // Note the use of a variable
    doContextQuery( openedContainer.getContainer(), "/desserts:item/product[text()=$aDessert]", context);

    return 0;


}
