#include <fstream>
#include <cstdio>

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

using namespace DbXml;

void usage()
{
       std::cerr <<  "This program retrieves DBXML documents using their document names. You should\n"
                 <<  "pre-load the container using loadExamplesData.[sh|cmd] before running this\n"
                 <<  "example.  You are only required to pass this command the path location of the\n"
                 <<  "database environment that you specified when you pre-loaded the examples\n"
                 <<  "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);
        std::cout << "\n";

        XmlResults results( container.queryWithXPath(0, XPath, &context ) );
        XmlValue value;
        while(results.next(value))
        {
            // Get the document's name and print it to the console
            XmlDocument theDocument( value.asDocument(0) );
            std::cout << "Document name: " << theDocument.getName() << std::endl;
            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");

    //Query for documents by their document names.
    doContextQuery( openedContainer.getContainer(), "//*[@dbxml:name='ZuluNut.xml']", context );
    doContextQuery( openedContainer.getContainer(), "//*[@dbxml:name='TrifleOrange.xml']", context );
    doContextQuery( openedContainer.getContainer(), "//*[@dbxml:name='TriCountyProduce.xml']", context );


    return 0;


}
