/*
 * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/taglib/DbBlobURLTag.java,v 1.9 2004/03/20 21:32:53 joepeer Exp $
 * $Revision: 1.9 $
 * $Date: 2004/03/20 21:32:53 $
 *
 * DbForms - a Rapid Application Development Framework
 * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 */
package org.dbforms.taglib;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.apache.log4j.Category;
import org.dbforms.config.DbFormsConfig;
import org.dbforms.config.DbFormsConfigRegistry;
import org.dbforms.config.Interceptor;

/**
 * #fixme docu to come
 *
 * @author  Joe Peer
 * @created  06 August 2002
 */
public class DbBlobURLTag extends DbBaseHandlerTag
      implements javax.servlet.jsp.tagext.TryCatchFinally
{

		protected String nameField;
		private static Category logCat =
			Category.getInstance(DbBlobURLTag.class.getName());
		private DbFormsConfig config;
	
   // --------------------------------------------------------- Public Methods
   // DbForms specific

   /**
    *  Description of the Method
    *
    * @return  Description of the Return Value
    * @exception  javax.servlet.jsp.JspException Description of the Exception
    */
   public int doEndTag() throws javax.servlet.jsp.JspException
   {
      try
      {

		//STEP 1: if namefield does not exist && the field is a blob field => look for the name
		this.nameField = null;
		//check field type
		if (this.getField().getFieldType().equals("blob") && this.nameField == "" || this.nameField == null){
			//Get the dbformsconfig object
			try {
				config = DbFormsConfigRegistry.instance().lookup();
				Vector interceptVector = config.getTableByName(this.getParentForm().getTable().getName()).getInterceptors();
				//STEP 2: look for the blobinterceptor
				for (int i=0;i<interceptVector.size();i++){
					Interceptor inter = (Interceptor) interceptVector.elementAt(i);
					if (inter.getClassName().equals("org.dbforms.event.BlobInterceptor")){
						//We found the blobinterceptor so break for loop
						i = interceptVector.size();
						//STEP 3: Loop through parameters for the namefield
						HashMap blobFieldData = new HashMap();
						String strId = null;
						for(Iterator iter = inter.getParams().entrySet().iterator(); iter.hasNext(); ) {
							Map.Entry me = (Map.Entry) iter.next();
							String key = (String) me.getKey();
							String value = (String) me.getValue();

							//if this is the field, get the id of blob-column(id)
							if (value.equals(this.getField().getName()) && strId == null){
								strId = key.substring(11);
								//reset Iterator
								iter = inter.getParams().entrySet().iterator();
							}
						
							//look for namefield value
							if (strId != null && key.equals("name-column" + strId)){
								this.nameField = value;
							}
						}
					}
				}
			} catch (Exception e) {
				logCat.error(e);
				throw new JspException("IO Error: " + e.getMessage());
			}
		}

         StringBuffer tagBuf = new StringBuffer(((HttpServletRequest) pageContext
               .getRequest()).getContextPath());

         tagBuf.append("/servlet/file?tf=").append(getTableFieldCode())
               .append("&keyval=").append(getKeyVal());
					
				// JPEer 03/2004
				 if(this.nameField != null) {
					 tagBuf.append("&nf=");
					 tagBuf.append(nameField);
				 }							 

         // append the defaultValue parameter;
         if (getDefaultValue() != null)
         {
            tagBuf.append("&defaultValue=" + getDefaultValue());

            //logCat.info("::doEndTag - defaultValue set to [" + defaultValue + "]");
         }

         pageContext.getOut().write(tagBuf.toString());
      }
      catch (java.io.IOException ioe)
      {
         throw new JspException("IO Error: " + ioe.getMessage());
      }

      return EVAL_PAGE;
   }

	 public void setNameField(String nameField) {
		 this.nameField = nameField;
	 }
	 
	 public String getNameField() {
		 return nameField;
	 }
	 
	 
   // ------------------------------------------------------ Protected Methods
   // DbForms specific

   /**
    *  Generates the decoded name.
    *
    * @return  The tableFieldCode value
    */
   private String getTableFieldCode()
   {
      StringBuffer buf = new StringBuffer();

      buf.append(getParentForm().getTable().getId());
      buf.append("_");
      buf.append(getField().getId());

      return buf.toString();
   }


   /**
    *  Gets the keyVal attribute of the DbBlobURLTag object
    *
    * @return  The keyVal value
    */
   protected String getKeyVal()
   {
      return getParentForm().getTable().getKeyPositionString(getParentForm().getResultSetVector());
   }
	/**
	 * DOCUMENT ME!
	 */
	public void doFinally()
	{
		super.doFinally();
	}

   /**
    * @see javax.servlet.jsp.tagext.TryCatchFinally#doCatch(java.lang.Throwable)
    */
   public void doCatch(Throwable t) throws Throwable
   {
      throw t;
   }

}
