/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2001-02 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.core.impl;

import java.io.*;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.util.IOUtil;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.EnvEngine;
import com.silverwrist.venice.except.*;

class ImageStore implements BinaryData
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  public static final short TYPE_USER_PHOTO = 1;
  public static final short TYPE_COMMUNITY_LOGO = 2;

  private static Category logger = Category.getInstance(ImageStore.class);

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private EnvEngine env;              // the execution environment
  private int imgid;
  private String type;
  private int length;

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  protected ImageStore(EnvEngine env, int imgid, String type, int length)
  {
    this.env = env;
    this.imgid = imgid;
    this.type = type;
    this.length = length;

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface BinaryData
   *--------------------------------------------------------------------------------
   */

  public String getMIMEType()
  {
    return type;

  } // end getMIMEType

  public String getFilename()
  {
    return null;

  } // end getFilename

  public int getLength()
  {
    return length;

  } // end getLength

  public InputStream getData() throws DataException
  {
    Connection conn = null;
    Statement stmt = null;
    InputStream rc = null;

    try
    { // open up a database connection
      conn = env.getConnection();
      stmt = conn.createStatement();

      // Create the SQL we need to retrieve the image.
      StringBuffer sql = new StringBuffer("SELECT data FROM imagestore WHERE imgid = ");
      sql.append(imgid).append(';');

      // Execute the query!
      ResultSet rs = stmt.executeQuery(sql.toString());
      if (!(rs.next()))
      { // there is no attachment data!
	logger.error("no image data to get");
	throw new DataException("There is no image data present.");

      } // end if

      // Since the InputStream we get from JDBC will probably go away when the connection is dropped, we
      // need to make a temporary copy of it.
      rc = new ByteArrayInputStream(IOUtil.load(rs.getBinaryStream(1)));

    } // end try
    catch (SQLException e)
    { // turn this into a DataException
      logger.error("DB error retrieving image: " + e.getMessage(),e);
      throw new DataException("unable to retrieve image data: " + e.getMessage(),e);

    } // end catch
    catch (IOException e)
    { // turn this into a DataException too
      logger.error("I/O error copying image data: " + e.getMessage(),e);
      throw new DataException("unable to retrieve image data: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure we release the connection before we go
      SQLUtil.shutdown(stmt);
      SQLUtil.shutdown(conn);

    } // end finally

    return rc;

  } // end getData

  /*--------------------------------------------------------------------------------
   * Static operations
   *--------------------------------------------------------------------------------
   */

  static final ImageStore loadImageByID(EnvEngine env, int id) throws DataException
  {
    if (logger.isDebugEnabled())
      logger.debug("loadImageByID # " + id);

    Connection conn = null;      // pooled database connection
    Statement stmt = null;

    try
    { // get a database connection
      conn = env.getConnection();
      stmt = conn.createStatement();

      StringBuffer sql = new StringBuffer("SELECT mimetype, length FROM imagestore WHERE imgid = ");
      sql.append(id).append(';');
      if (logger.isDebugEnabled())
	logger.debug("SQL: " + sql.toString());
      ResultSet rs = stmt.executeQuery(sql.toString());

      if (rs.next())  // create an object reference and return it
	return new ImageStore(env,id,rs.getString(1),rs.getInt(2));

      return null;  // no such image
      
    } // end try    
    catch (SQLException e)
    { // turn SQLException into data exception
      logger.error("DB error reading image entry: " + e.getMessage(),e);
      throw new DataException("unable to retrieve image entry: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure we release the connection before we go
      SQLUtil.shutdown(stmt);
      SQLUtil.shutdown(conn);

    } // end finally

  } // end loadImageByID

  static final int storeNewImage(Connection conn, short type, int owner, String mime, int length,
				 InputStream data) throws SQLException
  {
    // Create the SQL statement that inserts the image into the store.
    StringBuffer sql =
        new StringBuffer("INSERT INTO imagestore (typecode, ownerid, mimetype, length, data) VALUES (");
    sql.append(type).append(", ").append(owner).append(", '").append(mime).append("', ").append(length);
    sql.append(", ?);");
    if (logger.isDebugEnabled())
      logger.debug("SQL: " + sql.toString());

    PreparedStatement stmt = null;
    Statement stmt2 = null;

    try
    { // Prepare the statement, set the BLOB parameter, and execute it.
      stmt = conn.prepareStatement(sql.toString());
      stmt.setBinaryStream(1,data,length);
      stmt.executeUpdate();

      // Get the ID of the new image and return it.
      stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("SELECT LAST_INSERT_ID();");
      if (!(rs.next()))
	throw new InternalStateError("storeNewImage(): Unable to get new image ID!");
      return rs.getInt(1);

    } // end try
    finally
    { // shut down the statements to conserve resources
      SQLUtil.shutdown(stmt);
      SQLUtil.shutdown(stmt2);

    } // end finally

  } // end storeNewImage

  static final int storeNewImage(EnvEngine env, short type, int owner, String mime, int length,
				 InputStream data) throws DataException
  {
    if (logger.isDebugEnabled())
      logger.debug("storeNewImage: type " + type + ", owner " + owner + ", mime " + mime + ", len " + length);

    Connection conn = null;      // pooled database connection

    try
    { // get a database connection
      conn = env.getConnection();
      return storeNewImage(conn,type,owner,mime,length,data);
      
    } // end try
    catch (SQLException e)
    { // turn SQLException into data exception
      logger.error("DB error storing image entry: " + e.getMessage(),e);
      throw new DataException("unable to store image entry: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure we release the connection before we go
      SQLUtil.shutdown(conn);

    } // end finally

  } // end storeNewImage

  static final void replaceImage(Connection conn, int imgid, String mime, int length, InputStream data)
      throws SQLException
  {
    // Create the SQL statement that inserts the image into the store.
    StringBuffer sql = new StringBuffer("UPDATE imagestore SET mimetype = '");
    sql.append(mime).append("', length = ").append(length).append(", data = ? WHERE imgid = ").append(imgid);
    sql.append(';');
    if (logger.isDebugEnabled())
      logger.debug("SQL: " + sql.toString());

    PreparedStatement stmt = null;

    try
    { // Prepare the statement, set the BLOB parameter, and execute it.
      stmt = conn.prepareStatement(sql.toString());
      stmt.setBinaryStream(1,data,length);
      stmt.executeUpdate();

    } // end try
    finally
    { // shut down the sattement to conserve resources
      SQLUtil.shutdown(stmt);

    } // end finally

  } // end replaceImage

  static final void replaceImage(EnvEngine env, int imgid, String mime, int length, InputStream data)
      throws DataException
  {
    if (logger.isDebugEnabled())
      logger.debug("replaceImage: imgid " + imgid + ", mime " + mime + ", len " + length);

    Connection conn = null;      // pooled database connection

    try
    { // get a database connection
      conn = env.getConnection();
      replaceImage(conn,imgid,mime,length,data);

    } // end try
    catch (SQLException e)
    { // turn SQLException into data exception
      logger.error("DB error storing image entry: " + e.getMessage(),e);
      throw new DataException("unable to store image entry: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure we release the connection before we go
      SQLUtil.shutdown(conn);

    } // end finally

  } // end replaceImage

} // end class ImageStore
