#include "dbxml/DbXml.hpp"
#include "db_cxx.h"

class myDbEnv
{
    public:
        
        myDbEnv( const std::string &envHome ) 
            : environmentHome_( envHome ),
            dbEnv_( 0 ),
            dbEnvIsOpen_( false ),
            cFlags_(DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN)
        {
            if ( environmentHome_.empty() )
            {
                std::cerr << "Error opening the database environment. Found empty path string. " << std::endl;
            } else {
                try
                {
                    //redirect debugging information to std::cerr
                    dbEnv_.set_error_stream(&std::cerr);

                    //open the environment
                    dbEnv_.open(environmentHome_.c_str(),cFlags_, 0);
                    dbEnvIsOpen_ = true;
                }
                //if an exception gets caught here, almost certainly there will be 
                //  problems down the road. So simply exit rather than risk
                //  further problems.
                catch(DbException &e)
                {
                    std::cerr << "Error opening database environment: " << environmentHome_ << std::endl;
                    std::cerr << e.what() << std::endl;
                    exit( -1 );
                }
                catch(std::exception &e)
                {
                    std::cerr << "Error opening database environment: " << environmentHome_ << std::endl;
                    std::cerr << e.what() << std::endl;
                    exit( -1 );
                }
            }

        } //end myDbEnv constructor

        ~myDbEnv()
        {
            if ( dbEnvIsOpen_ )
            {
                //close the db env.
                try
                {
                    dbEnv_.close(0);
                }         
                catch(DbException &e)
                {
                    std::cerr << "Error closing database environment: " << environmentHome_ << std::endl;
                    std::cerr << e.what() << std::endl;
                }
                catch(std::exception &e)
                {
                    std::cerr << "Error closing database environment: " << environmentHome_ << std::endl;
                    std::cerr << e.what() << std::endl;
                }

            }

        } 

        inline const std::string &getDbEnvHome() const { return environmentHome_; }
        inline DbEnv &getDbEnv() { return dbEnv_; }        

    private:
        DbEnv dbEnv_;
        std::string environmentHome_;
        u_int32_t cFlags_;
        bool dbEnvIsOpen_;
};

