/*
  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.UnsupportedEncodingException;

/**
 * OFSPlainTextFile
 * <p>
 * A textfile which is delivered as is.
 */
public class OFSPlainTextFile extends OFSResourceFile {

  /* accessors */
  
  public String defaultDeliveryMimeType() {
    return "text/plain";
  }
  
  /* content as string */
  
  public String contentEncoding() {
    return null;
  }
  public String contentAsString() {
    String enc = this.contentEncoding();
    
    // TODO: directly read string from stream using a Reader
    byte[] contents = this.content();
    if (contents == null)
      return null;
    
    if (enc == null)
      return new String(contents);
    
    try {
      return new String(contents, enc);
    }
    catch (UnsupportedEncodingException e) {
      log.error("could not decode contents with charset '" + enc + "':" + this);
      return null;
    }
  }

  @Override
  public Exception writeContent(Object _content) {
    if (_content instanceof String) {
      String enc = this.contentEncoding();
      String s   = (String)_content;
      
      try {
        _content = enc != null ? s.getBytes(enc) : s.getBytes();
      }
      catch (UnsupportedEncodingException e) {
        log.error("could not encode contents with charset '" + enc + "':"+this);
        return e;
      }
    }
    
    return super.writeContent(_content);
  }

}
