package com.dbxml.db.admin.nodes;

/*
 * 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: DocumentsNode.java,v 1.11 2004/08/22 04:18:40 bradford Exp $
 */

import com.dbxml.db.admin.Admin;
import com.dbxml.db.client.CollectionClient;
import com.dbxml.util.Stopwatch;
import com.dbxml.util.dbXMLException;
import java.awt.Cursor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

/**
 * DocumentsNode
 */

public final class DocumentsNode extends AdminNode implements HasCollection, HasChildren, HasMenu {
   private static final AdminNode[] EmptyAdminNodes = new AdminNode[0];
   private static final Icon DocumentsIcon = new ImageIcon(DocumentsNode.class.getResource("docs_mini.gif"));

   public static final int ACTION_IMPORT = 0;

   private static final MenuItem[] Menu = new MenuItem[]{
      new MenuItem(ACTION_IMPORT, "Import Documents")
   };

   private CollectionClient col;

   public DocumentsNode(AdminNode parentNode, CollectionClient col) {
      super(parentNode);

      this.col = col;
   }

   public String getLabel() {
      return "Documents";
   }

   public Icon getIcon() {
      return DocumentsIcon;
   }

   public CollectionClient getCollection() {
      return col;
   }

   public AdminNode[] getChildren() {
      List list = new ArrayList();

      try {
         String[] docs = col.listKeys();
         for ( int j = 0; j < docs.length; j++ )
            list.add(new DocumentNode(this, col, docs[j]));
      }
      catch ( Exception e ) {
         // No Resources
      }

      return (AdminNode[])list.toArray(EmptyAdminNodes);
   }

   public MenuItem[] getMenu() {
      return Menu;
   }

   public int menuAction(int action) {
      Admin admin = Admin.getInstance();

      switch ( action ) {
         case ACTION_IMPORT: {
            try {
               JFileChooser fc = new JFileChooser();
               fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
               fc.setMultiSelectionEnabled(true);
               int result = fc.showDialog(admin, "Import");
               if ( result == JFileChooser.APPROVE_OPTION ) {
                  admin.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                  Stopwatch sw = new Stopwatch(true);
                  boolean docs = col.getCollectionType() == CollectionClient.TYPE_DOCUMENTS;
                  int count = 0;
                  int error = 0;
                  File[] files = fc.getSelectedFiles();
                  for ( int i = 0; i < files.length; i++ ) {
                     File file = files[i];
                     String docName = file.getName();
                     try {
                        if ( docs )
                           importDoc(docName, file);
                        else
                           importBin(docName, file);
                        count++;
                     }
                     catch ( Exception e ) {
                        error++;
                        admin.addMessage("Couldn't import '" + docName + "': "+e.getMessage());
                     }
                  }
                  sw.stop();
                  if ( error > 0 )
                     admin.addMessage(count+" Document(s) imported ("+error+" errors): "+sw.toString());
                  else
                     admin.setStatus(count+" Document(s) imported: "+sw.toString());
                  admin.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
               }
               return REFRESH_CHILDREN;
            }
            catch ( dbXMLException e ) {
               admin.addMessage(e.getMessage());
            }
         }
      }
      return REFRESH_NONE;
   }

   private void importBin(String docName, File file) throws Exception {
      FileInputStream fis = new FileInputStream(file);
      byte[] b = new byte[(int)file.length()];
      fis.read(b);
      fis.close();
      col.setValue(docName, b);
   }

   private void importDoc(String docName, File file) throws Exception {
      FileInputStream fis = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fis, 4096);
      InputStreamReader isr = new InputStreamReader(bis, "UTF8");
      char[] c = new char[(int)file.length()];
      int size = isr.read(c);
      isr.close();
      col.setDocumentAsText(docName, new String(c, 0, size));
   }

}
