package com.dbxml.db.common.filers;

/*
 * 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: FSFiler.java,v 1.4 2004/08/22 04:18:41 bradford Exp $
 */

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.data.Record;
import com.dbxml.db.core.data.RecordMetaData;
import com.dbxml.db.core.data.RecordSet;
import com.dbxml.db.core.data.Value;
import com.dbxml.db.core.filer.Filer;
import com.dbxml.db.core.filer.FilerException;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.db.core.transaction.TransactionLog;
import com.dbxml.util.Configuration;
import com.dbxml.util.SimpleConfigurable;
import com.dbxml.util.SimpleLockManager;
import com.dbxml.util.dbXMLException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.io.BufferedOutputStream;

/**
 * FSFiler allows you to use existing file systems withing dbXML.
 */

public final class FSFiler extends SimpleConfigurable implements Filer {
   private static final String LOCATION = "location";
   private static final String EXT = "ext";
   private static final String READONLY = "readonly";

   private SimpleLockManager locks = new SimpleLockManager();

   private Set extensions;

   private String location;
   private Collection collection;
   private File dir;
   private boolean opened;
   private boolean readOnly;

   public FSFiler() {
   }

   public String getName() {
      return "FSFiler";
   }

   public void setCollection(Collection collection) {
      this.collection = collection;
   }

   public void setConfig(Configuration config) throws dbXMLException {
      super.setConfig(config);
      location = config.getAttribute(LOCATION);
      readOnly = config.getBooleanAttribute(READONLY, readOnly);
      String exts = config.getAttribute(EXT);
      if ( exts != null && exts.trim().length() > 0 ) {
         extensions = new HashSet();
         StringTokenizer st = new StringTokenizer(exts);
         while ( st.hasMoreTokens() )
            extensions.add(st.nextToken());
      }
      dir = new File(location);
      opened = false;
   }

   private void checkOpened() throws DBException {
      if ( !opened )
         throw new FilerException(FaultCodes.COL_COLLECTION_CLOSED, "Filer is closed");
   }

   private void checkReadOnly() throws DBException {
      if ( readOnly )
         throw new FilerException(FaultCodes.COL_COLLECTION_READ_ONLY, "Filer is read-only");
   }

   public boolean close() {
      opened = false;
      return true;
   }

   public boolean open() {
      opened = (dir.exists() && dir.isDirectory());
      return opened;
   }

   public boolean drop() {
      opened = false;
      return true;
   }

   public boolean isOpened() {
      return opened;
   }

   public boolean exists() {
      return dir.exists();
   }

   public boolean create() {
      if ( !dir.exists() )
         return dir.mkdirs();
      else
         return true;
   }

   public void flush(Transaction tx) {
   }

   private RecordMetaData buildMetaData(File f) {
      HashMap meta = new HashMap(2);
      meta.put(RecordMetaData.MODIFIED, new Long(f.lastModified()));
      meta.put(RecordMetaData.SIZE, new Long(f.length()));
      return new RecordMetaData(meta);
   }

   public RecordMetaData getRecordMetaData(Transaction tx, Key key) throws DBException {
      checkOpened();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return null;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);

         if ( file.exists() && file.isFile() )
            return buildMetaData(file);
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return null;
   }

   public Record readRecord(Transaction tx, Key key) throws DBException {
      checkOpened();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return null;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);

         if ( file.exists() && file.isFile() ) {
            byte[] valueData = new byte[(int)file.length()];
            FileInputStream fis = new FileInputStream(file);
            RecordMetaData md = buildMetaData(file);

            fis.read(valueData);
            fis.close();

            return new Record(key, new Value(valueData), md);
         }
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return null;
   }

   public boolean writeRecord(Transaction tx, Key key, Value value) throws DBException {
      checkOpened();
      checkReadOnly();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return false;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);
         FileOutputStream fos = new FileOutputStream(file);
         BufferedOutputStream bos = new BufferedOutputStream(fos, 4096);
         value.streamTo(bos);
         bos.flush();
         bos.close();
         return true;
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return true;
   }

   public boolean deleteRecord(Transaction tx, Key key) throws DBException {
      checkOpened();
      checkReadOnly();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return false;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);
         return file.delete();
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return true;
   }

   public long getRecordCount(Transaction tx) throws DBException {
      checkOpened();

      File[] files = dir.listFiles(new FileFilter() {
         public boolean accept(File file) {
            return file.isFile() && isExtensionValid(file.getName());
         }
      });
      return files.length;
   }

   public RecordSet getRecordSet(Transaction tx) throws DBException {
      checkOpened();
      return new FSRecordSet(tx);
   }

   private boolean isExtensionValid(String fname) {
      if ( extensions != null ) {
         int idx = fname.lastIndexOf('.');
         if ( idx == -1 )
            return false;
         String ext = fname.substring(idx + 1);
         if ( !extensions.contains(ext) )
            return false;
      }
      return true;
   }

   public TransactionLog getTransactionLog() {
      return null;
   }


   /**
    * FSRecordSet
    */

   private class FSRecordSet implements RecordSet {
      private Transaction tx;
      private File[] files;
      private int pos;

      public FSRecordSet(Transaction tx) {
         this.tx = tx;
         files = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
               return file.isFile() && isExtensionValid(file.getName());
            }
         });
      }

      public synchronized boolean hasMoreRecords() {
         return pos < files.length;
      }

      public synchronized Record getNextRecord() throws DBException {
         File file = files[pos++];
         return readRecord(tx, new Key(file.getName()));
      }

      public synchronized Value getNextValue() throws DBException {
         return getNextRecord().getValue();
      }

      public synchronized Key getNextKey() {
         return new Key(files[pos++].getName());
      }
   }
}

