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

using namespace DbXml;
//some exception handling omitted for clarity

void usage()
{
        std::cerr << "This program adds a few simple XML documents to container 'my-container-name'\n"
                  << "You are only required to pass this program the path to where you want the\n"
                  << "database environment to be located: \n\n"
                  << "\t-h <dbenv directory>" << std::endl;
        exit( -1 );
}

int main(int argc, char **argv)
{
    std::string path2DbEnv;
    std::string theContainer = "my-container-name.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 );

    //myDbEnv and myXmlContainer open with transactions. All subsequent
    //writes to them must also be performed inside a transaction.

    //Get a transaction
    DbTxn *txn;
    theDBEnv.getDbEnv().txn_begin(0, &txn, 0);

    std::string document1 = "<aDoc><title>doc1</title><color>green</color></aDoc>";
    std::string document2 = "<aDoc><title>doc2</title><color>yellow</color></aDoc>";
    

    //Add the documents
    XmlDocument myXMLDoc;

    //Set the XmlDocument to the relevant string and then put it 
    // into the container.
    myXMLDoc.setContent( document1 );
    openedContainer.getContainer().putDocument(txn, myXMLDoc);

    //do it again for the second document
    myXMLDoc.setContent( document2 );
    openedContainer.getContainer().putDocument(txn, myXMLDoc);

    //Normally we would use a try/catch block to trap any exceptions.
    // In the catch, we should call txn->abort() to avoid leaving the
    // database in an indeterminate state in the event of an error.
    // However, this simple example avoids error handling so as to 
    // highlite basic concepts, so that step if omitted here as well.
    
    //Commit the writes. This causes the container write operations
    //  to be saved to the container.
    txn->commit(0);

    return 0;
}


    
