package org.dbxml.tools.command;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: ImportTree.java,v 1.23 2001/09/04 11:13:49 kstaken Exp $
 */
import java.util.Hashtable;
import java.io.*;

import org.dbxml.xml.dom.*;
import org.xmldb.api.base.*;
import org.xmldb.api.DatabaseManager;

import org.w3c.dom.*;

/**
 * ImportTree.java is designed to take a directory/file path and create a Collection
 * from it's name. The files within the directory are converted into Documents
 * and then stored into the newly created Collection with their filename as a document key
 *
 * NOTE:  If the collection passed in with the -c option already exists it will be overwritten!
 */

public class ImportTree extends Command {   
   Command addDocument = null;
   Command addCollection = null;
   
   public boolean execute(Hashtable table) throws Exception {
      Collection col = null;
      try {
         // Setup the creation commands we'll use to add documents and create
         // collections.
         addDocument = 
            (Command) Class.forName("org.dbxml.tools.command.AddDocument").newInstance();
   
         addCollection = 
            (Command) Class.forName("org.dbxml.tools.command.AddCollection").newInstance();
            
         String startcollection = null;

         // Verify that the correct command line parameters were passed in
         if (table.get("filePath") == null) {
            System.out.println("ERROR : Directory name and switch required");
            return false;
         }
         if (table.get("collection") == null) {
            System.out.println("ERROR : Collection name and switch required");
            return false;
         }
         
         startcollection = (String) table.get("collection");
         
         // Make sure the root collection exists
         String colstring = normalizeCollectionURI(startcollection);         
         if ((col = DatabaseManager.getCollection(colstring)) == null) {
            System.out.println("ERROR : Collection not found!");
            return false;
         }

         File startdir = new File((String) table.get("filePath"));

         // Make call to process, this is called recursively!
         process(startdir, startcollection, table);

      }
      catch (Exception e) {
         System.out.println("ERROR : " + e.getMessage());
         if (table.get("verbose").equals("true")) {
            org.dbxml.Debug.printStackTrace(e);
         }
         return false;
      }
      finally {
         // Be sure to close collection objects
         if (col != null) {
            col.close();
         }
      }

      return true;
   }

   // Recursive function to create collections/documents
   void process(File directory, String baseCollection, Hashtable table) 
         throws Exception {
     
      try {
         // The file extension to use for reading in files
         final String ext = (String) table.get("extension");

         // Make sure we received a directory so we don't create a collection
         // named after a file.
         if ( ! directory.isDirectory() ) {
            System.out.println("ERROR: The specified import path is not a directory " +
                  directory.getPath());            
            return;
         }

         // Create the collection for this directory.
         baseCollection = createCollection(baseCollection, directory.getName());
         
         // Get a directory listing and loop over
         File[] subdirs = directory.listFiles(new MyFileFilter(ext));

         for (int i = 0; i < subdirs.length; i++) {
            // Is this a directory?  If so, call ourselves recursively
            if (subdirs[i].isDirectory()) {
               process(subdirs[i], baseCollection, table);
            }
            else {
               // Otherwise we have a file so import it.
               importFile(baseCollection, subdirs[i].getAbsolutePath(),
                  subdirs[i].getName());                  
            }
         }
      }
      catch (Exception e) {
         System.out.println("ERROR : " + e.getMessage());
         if (table.get("verbose").equals("true")) {
            e.printStackTrace(System.out);
         }
         return;
      }
   }
      
   protected void importFile(String baseCollection, String path, String name)
         throws Exception {
      Hashtable table = new Hashtable();
      // Use functionality from AddDocument to add this document
      table.put("collection", baseCollection);
      table.put("filePath", path);
      table.put("nameOf", name);
            
      addDocument.execute(table);      
   }
   
   protected String createCollection(String baseCollection, String newCollection) 
         throws Exception {
      if (! newCollection.equals(".")) {
         Hashtable table = new Hashtable();
         table.put("collection", baseCollection);
         table.put("nameOf", newCollection);
                  
         addCollection.execute(table);
      }
      else {
         newCollection = "";
      }
      
      return baseCollection + "/" + newCollection;            
   }
}

/**
 * Allow us to filter directory listings over certain file extensions
 */
class MyFileFilter implements FileFilter {

   String extension = "";

   /**
    * TODO: Constructor for the MyFileFilter object
    *
    * @param ext Description of Parameter
    */
   public MyFileFilter(String ext) {
      extension = ext;
   }

   /**
    * TODO: Description of the Method
    *
    * @param file Description of Parameter
    * @return Description of the Returned Value
    */
   public boolean accept(File file) {
      if (extension != "") {
         return file.getName().endsWith("." + extension) || file.isDirectory();
      }
      else {
         return true;
      }
   }
}


