/**
 * Copyright (c) 2004 Red Hat, Inc. All rights reserved.
 *
 * 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 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
 *
 * Component of: Red Hat Application Server
 * 
 * Initial Developers: Aizaz Ahmed
 *                     Vivek Lakshmanan
 *                     Andrew Overholt
 *                     Matthew Wringe
 *
 */
package olstore.action;

import java.util.Vector;

import javax.servlet.http.*;
import javax.naming.Context;
import javax.naming.InitialContext;

import olstore.session.helper.ItemHelperLocal;
import olstore.session.helper.ItemHelperLocalHome;

import olstore.dto.ItemValue;
import olstore.dto.PictureValue;
import olstore.dto.PropertyValue;
import olstore.form.CreateItemForm;
import olstore.framework.EJBHomeFactory;

import org.apache.struts.action.*;
import org.apache.commons.beanutils.BeanUtils;


public class ItemCreateAction extends DemoBaseAction {
	
	/**
	 * Acts as a relay for all item related tasks with a default action
	 * 
	 */
	public ActionForward execute ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		//Throw an error if it doesn't equal of any of these?
		try {
			String action = ((CreateItemForm)form).getSubmitType();
			if ( action == null || action.equals("") )  {
				String itemId = ((CreateItemForm)form).getItemId();
				if ( itemId != null && ! itemId.equals("") ) {
					loadItem ( mapping, form, request, response );
				} else {
					CreateNewItem ( mapping, form, request, response );
				}
			} else if ( action.equals ( "updateProperties" ) ) {
				updateProperties ( mapping, form, request, response );
			} else if ( action.equals ( "updatePictures" ) ) {
				updatePictures ( mapping, form, request, response );
			} else if ( action.equals ( "changeType" ) ) {
				changeType ( mapping, form, request, response );
			} else if ( action.equals ( "saveItem" ) ) {
				return mapping.findForward ( "saveItem" );
			}
			
			return mapping.findForward ( "updateItem" );
			
			
		}
		
		catch (NumberFormatException n){
			ActionErrors errors = new ActionErrors();
			errors.add ("error", new ActionError("errors.not.int", n.getMessage() ));
			saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		catch ( Exception e ) {
			//Logging code here
			ActionErrors errors = new ActionErrors();
			errors.add("error", new ActionError("errors.item.load", e.getMessage() ));
			saveErrors(request, errors);
			// Return to same page
			return (new ActionForward(mapping.getInput()));
		}
		
	}
	
	
	public void CreateNewItem ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		//Get the default selected type
		Context context = new InitialContext();
		String type = (String) context.lookup ( "java:comp/env/DEFAULT_TYPE" );
		
		//Add an empty default Picture
		//This get method creates the specified index element, see form
		//for details
		((CreateItemForm)form).getPic ( 0 );
		
		//Load up the default properties for default type
		EJBHomeFactory factory = EJBHomeFactory.getInstance();
		ItemHelperLocalHome itemHelperHome = (ItemHelperLocalHome) factory.getLocalHome ( EJBHomeFactory.ITEM_HELPER );
		ItemHelperLocal itemHelper = itemHelperHome.create();
		Vector propValueArr = itemHelper.getPropertiesForType ( type );
		
		((CreateItemForm)form).setProperties ( propValueArr );
	}
	
	
	/**
	 * This method updates the number of properties 
	 * for display. The only validation that should take place in this
	 * particular action is that the total number of fields is a valid
	 * integer
	 */
	public void updateProperties ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		Vector propValueArr = ((CreateItemForm)form).getProperties();
		String numPropsStr =  ((CreateItemForm)form).getNumProps();
		int numProps = Integer.parseInt ( numPropsStr );
		
		
		
		// if the number is smaller than the present length, then truncate
		// the existing array
		if (  numProps < propValueArr.size() ) {
			for ( int i = propValueArr.size() -1 ; i > numProps - 1 ; i-- ) {
				propValueArr.remove ( i );
			}
		}
		
		// If the number is larger, then grow the ArrayList
		if ( numProps > propValueArr.size() ) {
			for ( int i = propValueArr.size() ; i < numProps ; i++ ) {
				propValueArr.add ( new PropertyValue() );
			}
		}
		
		((CreateItemForm)form).setProperties ( propValueArr ) ;
		
	}
	
	/**
	 * This method updates the number of properties 
	 * for display. The only validation that should take place in this
	 * particular action is that the total number of fields is a valid
	 * integer
	 */
	public void updatePictures ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		Vector propValueArr = ((CreateItemForm)form).getPictures();
		String numPicsStr =  ((CreateItemForm)form).getNumPics();
		int numPics = Integer.parseInt ( numPicsStr );
		
		if (numPics<=0){
			//ActionErrors errors = new ActionErrors();
			//errors.add ("error", new ActionError("errors.not.int", "The Number of Fields for Pictures " ));
			//saveErrors(request,errors);
			throw new Exception("The number of Picture Fields must be a postive interger") ;
		}
		
		// if the number is smaller than the present length, then truncate
		// the existing array
		if (  numPics < propValueArr.size() ) {
			for ( int i = propValueArr.size() -1 ; i > numPics - 1 ; i-- ) {
				propValueArr.remove ( i );
			}
		}
		
		// If the number is larger, then grow the ArrayList
		if ( numPics > propValueArr.size() ) {
			for ( int i = propValueArr.size() ; i < numPics ; i++ ) {
				propValueArr.add ( new PictureValue() );
			}
		}
		
		((CreateItemForm)form).setPictures ( propValueArr ) ;
		
	}
	
	
	/**
	 * This action loads up the default properties for a given type
	 * for an existing form. (It preserves the values that the
	 * user has entered)
	 */
	public void changeType ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		CreateItemForm createForm = (CreateItemForm)form;
		String newType = createForm.getTypeId();
		EJBHomeFactory factory = EJBHomeFactory.getInstance();
		ItemHelperLocalHome itemHelperHome = (ItemHelperLocalHome) factory.getLocalHome ( EJBHomeFactory.ITEM_HELPER );
		ItemHelperLocal helperLocal = itemHelperHome.create();
		Vector newProps = helperLocal.getPropertiesForType ( newType );
		
		//change the oldProps to have the new prop names (preserve values)
		int i = 0;
		for (; i < newProps.size() ; i++ ) {
			PropertyValue prop = createForm.getProp ( i );
			prop.setName ( ((PropertyValue)newProps.get(i)).getName() );
		}
		
		// erase any extras that might be left
		Vector oldProps = createForm.getProperties();
		int size = oldProps.size();
		for ( int j=0; j < size - i; j++ ) {
			oldProps.remove ( oldProps.size() - 1 );
		}
	}
	
	
	public void loadItem ( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response
	) throws Exception {
		
		CreateItemForm createForm = (CreateItemForm)form;
		String itemId = createForm.getItemId();
		EJBHomeFactory factory = EJBHomeFactory.getInstance();
		ItemHelperLocalHome itemHelperHome = (ItemHelperLocalHome) factory.getLocalHome ( EJBHomeFactory.ITEM_HELPER );
		ItemHelperLocal itemHelper = itemHelperHome.create();
		
		ItemValue itemVal = itemHelper.getItemValueForId ( itemId );
		BeanUtils.copyProperties ( createForm, itemVal );
	}
	
	
}
