#include <fstream>
#include <cstdio>
#include <cassert>

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

using namespace DbXml;

void usage()
{
      std::cerr   <<  "This program performs various XPath queries against a DBXML container and then\n"
                  <<  "retrieves information of interest from the retrieved document(s).  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 data:\n\n"

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

std::string getValue( const XmlDocument &document, const std::string &XPath, XmlQueryContext &context )
{
    /////////////////////////////////////////////////////////////////////////////////
    ///////////    Return specific information from a document. ///////////////////// 
    ///////////   !!!!!! Assumes a result set of size 1 !!!!!!! /////////////////////
    /////////////////////////////////////////////////////////////////////////////////
    

    // Exception handling omitted....
    
    //We don't want a document, we want a specific value. So set the
    //return type to Result Values
    context.setReturnType( XmlQueryContext::ResultValues );

    //Perform the query
    XmlResults result = document.queryWithXPath(XPath, &context);

    //We require a result set size of 1.
    assert( result.size() == 1 );

    //Get the value. If we allowed the result set to be larger than size 1,
    //we would have to loop through the results, processing each as is
    //required by our application.
    XmlValue value;
    result.next(value);

    //Set the result type back to Result Document
    context.setReturnType( XmlQueryContext::ResultDocuments );
    return value.asString( 0 );
        
}

void getDetails( const XmlContainer &container, const std::string &XPath, XmlQueryContext &context )
{
    ////////////////////////////////////////////////////////////////////////
    //////  Performs an XPath query (in 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;
        std::cout << "\n\tProduct : Price : Inventory Level\n";
        while( results.next(value) )
        {
            /// Retrieve the value as a document
            XmlDocument theDocument( value.asDocument(0) );

            /// Obtain information of interest from the document. Note that the 
            //  wildcard in the XPath expression allows us to not worry about what
            //  namespace this document uses.
            std::string item = getValue( theDocument, "/*/product/text()", context);
            std::string price = getValue( theDocument, "/*/inventory/price/text()", context);
            std::string inventory = getValue( theDocument, "/*/inventory/inventory/text()", context);

            std::cout << "\t" << item << " : " << price << " : " << inventory << std::endl;

        }
        std::cout << "\n";
        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");

    //get details on Zulu Nuts
    getDetails( openedContainer.getContainer(), "/fruits:item/product[text() = 'Zulu Nut']", context);

    //get details on all fruits that start with 'A'
    getDetails( openedContainer.getContainer(), "/vegetables:item/product[starts-with(text(),'A')]", context);

    return 0;
}
