package com.dbxml.db.client.xmldb;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: DatabaseImpl.java,v 1.2 2004/02/12 00:17:55 bradford Exp $
 */

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

import com.dbxml.db.client.CollectionClient;
import com.dbxml.db.client.dbXMLClient;
import com.dbxml.db.client.xmlrpc.dbXMLClientImpl;
import com.dbxml.db.server.dbXML;
import com.dbxml.util.SoftHashMap;
import com.dbxml.util.dbXMLException;

import org.xmldb.api.base.*;

/**
 * DatabaseImpl implements the XML:DB Database interface for dbXML.  The
 * URL form is: dbxml://[server]:[port]/[collection-path]
 */

public final class DatabaseImpl implements Database, Configurable {
   private static final String DEFAULT_DRIVER = dbXMLClientImpl.class.getName();

   private static final String NAME = "dbxml";
   private static final String DBXML_PREFIX = NAME+':';
   private static final String HTTP_PREFIX = "http:";
   private static final String CONFORMANCE_LEVEL = "1";

   private static final String DRIVER = "driver";
   private static final String CONNECTION = "connection";

   private Properties props = new Properties();
   private Map clientCache = Collections.synchronizedMap(new SoftHashMap());

   public String getName() throws XMLDBException {
      return NAME;
   }

   public String getProperty(String name) throws XMLDBException {
      return props.getProperty(name);
   }

   public void setProperty(String name, String value) throws XMLDBException {
      props.setProperty(name, value);
   }

   public Collection getCollection(String uri, String username, String password) throws XMLDBException {
      // Morph into an HTTP URI so it can be parsed by the URL class
      if ( uri.startsWith(DBXML_PREFIX) )
         uri = HTTP_PREFIX + uri.substring(DBXML_PREFIX.length());

      URL url = null;
      try {
         url = new URL(uri);
      }
      catch ( MalformedURLException e ) {
         throw new XMLDBException(ErrorCodes.INVALID_URI, e.getMessage());
      }

      String host = url.getHost();
      int port = url.getPort();
      String path = url.getPath();

      String conID = getConnectionID(host, port, username, password);
      dbXMLClient dbClient = (dbXMLClient)clientCache.get(conID);
      if ( dbClient == null ) {
         String driver = props.getProperty(DRIVER, DEFAULT_DRIVER);
         try {
            dbClient = (dbXMLClient)Class.forName(driver).newInstance();
         }
         catch ( Exception e ) {
            throw new XMLDBException(ErrorCodes.INVALID_DATABASE, "Driver '"+driver+"' could not be instantiated");
         }

         String connection = props.getProperty(CONNECTION);
         if ( connection != null )
            dbClient.setProperty(CONNECTION, connection);

         if ( host != null && !host.equals(dbXML.DEFAULT_HOST) )
            dbClient.setProperty(dbXMLClient.HOST, host);
         if ( port != dbXML.DEFAULT_PORT )
            dbClient.setProperty(dbXMLClient.PORT, Integer.toString(port));
         if ( username != null )
            dbClient.setProperty(dbXMLClient.USER, username);
         if ( password != null )
            dbClient.setProperty(dbXMLClient.PASS, password);

         try {
            dbClient.connect();
            clientCache.put(conID, dbClient);
         }
         catch ( dbXMLException e ) {
            throw new XMLDBException(ErrorCodes.NO_SUCH_DATABASE, e.getMessage());
         }
      }

      try {
         CollectionClient colClient = dbClient.getCollection(path);
         if ( colClient != null )
            return new CollectionImpl(colClient);
         else
            throw new XMLDBException(ErrorCodes.NO_SUCH_COLLECTION, "No such Collection at '"+uri+"'");
      }
      catch ( dbXMLException e ) {
         throw new XMLDBException(ErrorCodes.NO_SUCH_COLLECTION, e.getMessage());
      }
   }

   public boolean acceptsURI(String uri) throws XMLDBException {
      return uri.startsWith(DBXML_PREFIX);
   }

   public String getConformanceLevel() throws XMLDBException {
      return CONFORMANCE_LEVEL;
   }

   private String getConnectionID(String host, int port, String user, String pass) {
      StringBuffer sb = new StringBuffer(32);
      sb.append(DBXML_PREFIX);
      if ( user != null ) {
         sb.append(user);
         sb.append(':');
         sb.append(pass);
         sb.append('@');
      }
      sb.append(host);
      sb.append(':');
      sb.append(Integer.toString(port));
      sb.append(':');
      return sb.toString();
   }
}
