package com.sleepycat.dbxml.examples.gettingStarted;

import java.io.*;
import java.util.*;

import com.sleepycat.dbxml.examples.gettingStarted.myDbEnv;
import com.sleepycat.dbxml.*;
import com.sleepycat.db.*;

public class myXmlContainer
{
    //Constructor that opens the container in a database environment
    public myXmlContainer( String containerName, myDbEnv myDbEnv_ ) throws Throwable
    {
        dbEnv_ = myDbEnv_.getDbEnv();
        container_ = new XmlContainer( dbEnv_, containerName, 0 );
        //Uncomment the next line in order to see debugging information
        //container_.setLogLevel(XmlContainer.LEVEL_ALL, true);
        containerName_ = containerName;
        try
        {
            //Create a transaction and open the container
            DbTxn txn = dbEnv_.txnBegin(null, 0);
            container_.open(txn, cFlags_, 0);
            txn.commit(0);
        //XmlException  extends DbException, which in turn extends Exception. So just catching
        // Exception gets everything.
        } catch (Exception e) {
            System.err.println("Error opening container: " + containerName_);
            System.err.println("      Exception message: " + e.getMessage());
            throw e;
        }
    }

    //Constructor that opens the container without a database environment
    public myXmlContainer( String containerName ) throws Throwable
    {
        container_ = new XmlContainer(null, containerName, 0);
        containerName_ = containerName;
        try
        {
            //Open the container. No environment here, so we won't use transactions.
            container_.open(null, cFlags_, 0);
        // Catching Exception gets everything.
        } catch (Exception e) {
            System.err.println("Error opening container: " + containerName_);
            System.err.println("      Exception message: " + e.getMessage());
            throw e;
        }
    }

    public String getContainerName() { return containerName_; }

    public XmlContainer getContainer() { return container_; }

    public DbEnv getDbEnv() throws Throwable
    {
        if (dbEnv_ == null) {
            throw new Exception("Attempted to obtain a database environment from a container that was not opened in an environment.");
        }

        return dbEnv_;
    }

    public void cleanup() throws Throwable
    {
       if (container_.isOpen()) {
            container_.close( 0 );
       } else {
          throw new Exception("Attempt to close container " + containerName_ + ", but it is not opened.");
       }
    }


    private XmlContainer container_ = null;
    private int cFlags_ = Db.DB_CREATE;
    private File path2DbEnv_ = null;
    private DbEnv dbEnv_ = null;
    private String containerName_;

}

