/*
  Copyright (C) 2007 Helge Hess

  This file is part of JOPE.

  JOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  JOPE 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 Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with JOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/
package org.opengroupware.jope.ofs;

import java.io.IOException;
import java.io.InputStream;

import org.opengroupware.jope.foundation.NSException;

public class OFSFile extends OFSBaseObject {
  
  /* accessors */
  
  public String defaultDeliveryMimeType() {
    return "application/octet-stream";
  }
  
  /* content */

  public InputStream openStream() {
    if (this.fileManager == null)
      return null;
    
    return this.fileManager.openStreamOnPath(this.storagePath);
  }
  
  protected static long contentLoadSizeLimit = 128 * 1024 * 1024; /* 128MB */
  
  public byte[] content() {
    // TODO: move to Foundation (NSReadStreamAsByteArray() or sth like this)
    long size = this.size();
    if (size == 0) return new byte[0]; /* empty file */
    
    InputStream in = this.openStream();
    if (in == null) return null;
    
    if (size > contentLoadSizeLimit || size > Integer.MAX_VALUE) {
      log.error("refusing to load a huge file into memory: " + this +
          "\n  limit: " + contentLoadSizeLimit +
          "\n  size:  " + size);
      return null;
    }
    
    byte[] contents = null;
    try {
      contents = new byte[(int)size /* we check the limit above */];
      byte[] buffer = new byte[4096];
      int gotlen, pos = 0;
      
      while ((gotlen = in.read(buffer)) != -1) {
        System.arraycopy(buffer, 0, contents, pos, gotlen);
        pos += gotlen;
      }
    }
    catch (IOException ioe) {      
      // TODO: what to do with failed requests?
      log().warn("could not read content of file: " + this);
      contents = null;
    }
    finally {
      if (in != null) {
        try {
          in.close();
        }
        catch (IOException e) {
          log().warn("could not close input stream", e);
          e.printStackTrace();
        }
      }
    }
    return contents;
  }
  
  public Exception writeContent(Object _content) {
    // TODO: add qualifier for validation (etag)
    return new NSException("not implemented");
  }
  
  /* description */

  @Override
  public void appendAttributesToDescription(StringBuilder _d) {
    super.appendAttributesToDescription(_d);
  }
}
