package com.mycompany.commerce.customization.catalog;
/*
 *-------------------------------------------------------------------
 * Licensed Materials - Property of IBM
 *
 * WebSphere Commerce
 *
 * (c) Copyright International Business Machines Corporation.
 *     2006
 *     All rights reserved.
 *
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *-------------------------------------------------------------------
 */

//*---------------------------------------------------------------------
//* The sample contained herein is provided to you "AS IS".
//*
//* It is furnished by IBM as a simple example and has not been  
//* thoroughly tested under all conditions.  IBM, therefore, cannot
//* guarantee its reliability, serviceability or functionality.  
//*
//* This sample may include the names of individuals, companies, brands 
//* and products in order to illustrate concepts as completely as 
//* possible.  All of these names are fictitious and any similarity
//* to the names and addresses used by actual persons or business
//* enterprises is entirely coincidental.
//*---------------------------------------------------------------------
//*


import java.math.BigInteger;
import java.util.logging.Logger;

import com.ibm.commerce.beans.DataBeanManager;
import com.ibm.commerce.catalog.beans.CatalogEntryDataBean;
import com.ibm.commerce.catalog.facade.server.exception.CatalogApplicationException;
import com.ibm.commerce.catalog.facade.server.exception.CatalogSystemException;
import com.ibm.commerce.catalog.facade.server.helpers.CatalogComponentHelper;
import com.ibm.commerce.catalog.facade.server.helpers.CatalogServerConstants;
import com.ibm.commerce.catalog.facade.server.logging.CatalogApplicationMessageKeys;
import com.ibm.commerce.catalog.facade.server.logging.CatalogSystemMessageKeys;
import com.ibm.commerce.exception.ECException;
import com.ibm.commerce.foundation.client.util.oagis.RelationalExpression;
import com.ibm.commerce.foundation.common.util.logging.LoggingHelper;
import com.ibm.commerce.search.beans.CatEntrySearchListDataBean;
import com.ibm.commerce.catalog.facade.server.commands.*;
/**
 * This task command retrieves a list of Catalog Entries according to the minimum 
 * and maximum price specified by client. The list contains
 * <code>CatalogEntryDataBean</code> objects populated with the all the
 * available data. The search criteria is specified as a xpath query. To
 * retrieve various parameters in the xpath query methods are available in
 * <code>SelectionCriteriaMapper</code>. Following is the list of parameters
 * passed through xpath query: <br>
 * <ul>
 * <li>minPrice : Sets the value for the minimum price that will be used for the search.
 * 	This minimum price is searched in the <code>OFFERPRICE</code> column of the <code>PRICE</code> table.
 * </li>
 * <br>
 * <li>maxPrice : Sets the value of the maximum price that will be used for the search.
 * This maximum price is searched in the <code>OFFERPRICE</code> column of the <code>PRICE</code> table.
 * </li>
 * <br>
 * <li>currency: Sets the currency that will be used for the search. 
 * The currency is based on a value in the <code>OFFERPRICE</code> column of the <code>CURRENCY</code> table.
 * <br>
 * It is assumed that both currency values set in the command are the same. Even if the two currency values are different <br>
 * Only the first one will be used by the command. <br>
 * </li>
 * </ul>
 *  
 */
public class FetchCatalogEntryByPriceRangeTaskCmdImpl extends AbstractFetchCatalogEntrySOICmdImpl {

    /**
     * Constructor
     */
    public FetchCatalogEntryByPriceRangeTaskCmdImpl() {
        super();
    }

    /**
     * IBM Copyright notice field.
     */
    private static final String COPYRIGHT = com.ibm.commerce.copyright.IBMCopyright.SHORT_COPYRIGHT;
    
    private static final String CLASSNAME = FetchCatalogEntryByPriceRangeTaskCmdImpl.class.getName();

    private static final Logger LOGGER = LoggingHelper.getLogger(FetchCatalogEntryByPriceRangeTaskCmdImpl.class);

    private com.ibm.commerce.oagis9.datatypes.GetType iGetVerb = null;

    private com.ibm.commerce.oagis9.datatypes.ShowType iShowVerb = null;

    private java.util.List iCatalogs = null;

    private String userId = null;

    /**
     * This method searches for and retrieves catalog entries based on the search<br>
     * criteria passed in by the client. This method uses the<br>
     * <code>CatEntrySearchListDataBean</code> which returns an array of<br>
     * <code>CatalogEntryDataBean</code> which are then populated with all the available<br>
     * data. These databeans are stored into a <code>Vector</code> and<br>
     * returned back to calling method in the super class.<br>
     * This method will search based on maximum and minimum price specified for all types of catalog entries<br>
     * including products, items, bundles, dynamic kits, and packages.<br>
     * 
     * @return Returns a <code>Vector</code> containing objects of type <code>CatalogEntryDataBean</code>.
     * @exception <code>CatalogSystemException</code>,
     * @exception           <code>CatalogApplicationException</code>
     * @throws <code>CatalogSystemException</code>
     * @throws <code>CatalogApplicationException</code>
     */
    public java.util.Vector fetchCatalogEntrys() throws CatalogSystemException, CatalogApplicationException {
        
    	//A constant to hold the name of the method which can be used for logging.
    	final String METHODNAME = "fetchCatalogEntrys()";
    	
    	
    	//Telling the logger that this method has started.
        if (LoggingHelper.isEntryExitTraceEnabled(LOGGER)) {
            LOGGER.entering(CLASSNAME, METHODNAME);
        }

        
        
        //The reference ID that was set in the getVerb which was passed into this Fetch command to be used for paging.
        String wc_refID = null;
 
        //A list of parameters with a specified key retrieved from the XPath
        java.util.List lRelExpr = null;
        
        //A list of sub-parameters retrieved from the parameter specified in lRelExpr;
        java.util.List searchTermList = null;
        
        //A vector of catalog entries that will be returned from this command to the compose command.
        java.util.Vector catalogEntries = new java.util.Vector();
        
        //A map of parameters from the XPath.
        java.util.Map mapQueryParameters = null;
        
        //Action can be "-Read", "-Write", "Execute". We are using 'Execute'
        String action = CatalogServerConstants.ACCESS_CONTROL_ACTION; 
       
        //The number of elements to return in a page to be used for paging.
        BigInteger wc_displayNum = null;
        
        //The element number to start with when results are returned to be used for paging.
        BigInteger wc_beginIndex = null;
        
        //Determine whether or not the user is allowed to execute this command
        if (!CatalogComponentHelper.isAllowed(CatalogServerConstants.FETCH_CATALOG_ENTRY_ACCESS_CONTROL_COMMAND,action)) {
        	//If the user is not allowed to execute this command then throw an exception.
            throw new CatalogApplicationException(CatalogApplicationMessageKeys._APP_ACCESS_CHECK_FAILED,
                    new Object[] { userId, action, CLASSNAME }, CLASSNAME, METHODNAME);
        } else {
        	
        	//If the user is allowed to execute this command then retrieve the information from the XPath and put it into the CatEntrySearchListDataBean.
        	
            try {

            	//An array of type CatalogEntryDataBean to be used to hold the set of catalog entries retrieved from the search performed by the CatEntrySearchListDataBean.
                CatalogEntryDataBean[] resultCatalogEntryDataBean = null;
               
                //The number of catalog entries returned in the current search to be compared to the total record count to see if there are more pages.
                int recordCount = 0;
                
                //The minimum price to be retrieved from the XPath.
                String minPrice = new String("0");
                
                //The maximum price to be retrieved from the XPath.
                String maxPrice = new String("0");
                
                //The currency to be retrieved from the XPath.
                String currency = new String("USD");
                
                //The total number of results returned from the search by the CatEntrySearchListDataBean. This value is compared to the record count to determine if there are more pages.
                String totalRecordCount = null;
                
                //The result to start with when returning a specified number of results to be used for paging.
                String beginIndex = null;

                // The CatEntrySearchListDataBean which will perform the search and return an array of type CatalogEntryDataBean holding the results.
                CatEntrySearchListDataBean catalogDataBean = new CatEntrySearchListDataBean();
                
                //Gets the list of parameters from the XPath expression.
                mapQueryParameters = getSelectionCriteriaMapper().getQueryParameters();
                          
                //If the XPath contains a list Price attributes then retrieve them
                if (mapQueryParameters.containsKey("Price")) {
                    //Get the list of Price attributes
                	lRelExpr = (java.util.List) mapQueryParameters.get("Price");
                   
                	//Get the first Price attribute which is for maximum price as defined in the XPath
                	searchTermList = ((RelationalExpression) lRelExpr.get(0)).getValues();
                    
                	//Set the maximum price from the Price attribute
                	maxPrice = ((String) searchTermList.get(0)).trim();
                   
                    //Set the maximum price in the CatEntrySearchListDataBean
                    catalogDataBean.setMaxPrice(maxPrice);
                    
                    //Get the second Price attribute which is for the minimum price as defined in the XPath
                    searchTermList = ((RelationalExpression) lRelExpr.get(1)).getValues();
                   
                    //Set the minimum price from the value of the Price attribute
                    minPrice = ((String) searchTermList.get(0)).trim();
                   
                    //Set the minimum price in the CatEntrySearchListDataBean
                    catalogDataBean.setMinPrice(minPrice);
                }
                  
                //If the XPath contains a currency attribute then retrieve it
                if (mapQueryParameters.containsKey("currency")) {
                    lRelExpr = (java.util.List) mapQueryParameters.get("currency");
                   
                    searchTermList = ((RelationalExpression) lRelExpr.get(0)).getValues();
                    currency = ((String) searchTermList.get(0)).trim();
                   
                    //Set the currency value in the CatEntrySearchListDataBean
                    catalogDataBean.setCurrency(currency);
                   
                }

                /*//*********Added for Pagigng***********/
                
                //The number of results to return in a page
                wc_displayNum = getGet().getMaxItems();
               
                //The index of the result to start with when returning a specified number of results for paging.
                wc_beginIndex = getGet().getRecordSetStartNumber();
               
                //The reference ID of the record set used for paging to maintain a page state.
                wc_refID = getGet().getRecordSetReferenceId();              
               
                //Set the page size in the CatEntrySearchListDataBean
                if (wc_displayNum != null ){
                    catalogDataBean.setPageSize(wc_displayNum.toString());
                }
                
                //Set the beginning index in the CatEntrySearchListDataBean
                if (wc_beginIndex != null ){
                    catalogDataBean.setBeginIndex(wc_beginIndex.toString());
                }

              
                	//Try to retrieve the results from the CatEntrySearchListDataBean
                    try {
                        //Searching for all types of catalog entries as it is not specified in xPath.
                    	catalogDataBean.setIsBundle(true);
                    	catalogDataBean.setIsDynamicKit(true);
                    	catalogDataBean.setIsItem(true);
                    	catalogDataBean.setIsPackage(true);
                    	catalogDataBean.setIsProduct(true);
                    	
                    	
                    	//Activate the CatEntrySearchListDataBean
                    	DataBeanManager.activate(catalogDataBean);
                    	
                    	//Get the array of type CatalogEntryDataBean which holds all the resulting catalog entries.
                        resultCatalogEntryDataBean = catalogDataBean.getResultList();
                        
                        //The total number of results
                        totalRecordCount = catalogDataBean.getResultCount();
                        
                        //The index that the results started from for paging.
                        beginIndex = catalogDataBean.getBeginIndex();
                    } catch (ECException e) {
                        if (LoggingHelper.isTraceEnabled(LOGGER)){
                            LOGGER.logp(LoggingHelper.DEFAULT_TRACE_LOG_LEVEL, CLASSNAME, METHODNAME,
                                    CatalogApplicationMessageKeys._APP_CATENTRY_NO_RECORDS_FOUND_SEARCH,
                                    new Object[] { minPrice, maxPrice });
                        }
                    }
                          

                   
                if (resultCatalogEntryDataBean != null) 
                {
                	//The number of results returned in the page
                    recordCount = resultCatalogEntryDataBean.length;
                   
                    //Add each result to a vector of type CatalogEntryDataBean which will be sent to the compose command.
                    for (int i = 0; i < recordCount; i++) {
                        catalogEntries.add(resultCatalogEntryDataBean[i]);
                    }
                    
                    //If there are more results set the record set complete indicator to false in the show.
                    if(recordCount != Integer.parseInt(totalRecordCount))
                    {
                        getShowCatalogEntryDataArea().getShow().setRecordSetCompleteIndicator(false);
                    }
                    else
                    {
                    	//If there are no more then set the record set complete indicator to true in the show.
                        getShowCatalogEntryDataArea().getShow().setRecordSetCompleteIndicator(true);
                    }
                          
                    //Set the number of results returned on the page in the show
                    getShowCatalogEntryDataArea().getShow().setRecordSetCount(BigInteger.valueOf(recordCount));
                   
                    if(totalRecordCount != null)
                    {
                    	//Set the total number of results available on all pages in the show
                        getShowCatalogEntryDataArea().getShow().setRecordSetTotal(BigInteger.valueOf(Long.parseLong(totalRecordCount)));
                        
                    }
                    
                    if(wc_refID != null)
                    {
                    	//Set the reference ID in the show.
                        getShowCatalogEntryDataArea().getShow().setRecordSetReferenceId(wc_refID);
                    }
                    if(beginIndex != null)
                    {
                    	//set the beginning index of the result set into the show.
                        getShowCatalogEntryDataArea().getShow().setRecordSetStartNumber(BigInteger.valueOf(Long.parseLong(beginIndex)));
                        
                    }
                    

                }
                
            } catch (Exception e) {
                throw new CatalogSystemException(CatalogSystemMessageKeys._SYS_GENERIC, new Object[] { e
                        .getMessage() }, CLASSNAME, METHODNAME);
            }
        }

        //Tell the logger that the method is ending.
        if (LoggingHelper.isEntryExitTraceEnabled(LOGGER)) {
            LOGGER.exiting(CLASSNAME, METHODNAME, catalogEntries);
        }
        
        return catalogEntries;
    }

    /**
     * This method returns the show verb response that represent the results of
     * the fetch operation.
     * 
     * @return The show verb response.
     * @see com.ibm.commerce.catalog.facade.server.commands.FetchCatalogCmd#getShow()
     */
    public com.ibm.commerce.oagis9.datatypes.ShowType getShow() {
        return iShowVerb;
    }

    /**
     * This method sets the show response to associated with the fetch
     * operation.
     * 
     * @param showVerb
     *            The responding show verb.
     */
    public void setShow(com.ibm.commerce.oagis9.datatypes.ShowType showVerb) {
        iShowVerb = showVerb;
    }

    /**
     * This method sets the list of Catalog Entries that result from executing
     * the fetch operation.
     * 
     * @param catalogs
     *            The list of Catalog Entries that where retrieved.
     */
    protected void setCatalogs(java.util.List catalogs) {
        iCatalogs = catalogs;
    }

    /**
     * This method sets the get expression for the fetch operation. This get
     * expression can also include the paging information to base the results to
     * show.
     * 
     * @param getVerb
     *            The get expression.
     * @see com.ibm.commerce.catalog.facade.server.commands.FetchCatalogCmd#setGet(com.ibm.commerce.oagis9.datatypes.GetType)
     */
    public void setGet(com.ibm.commerce.oagis9.datatypes.GetType getVerb) {
        iGetVerb = getVerb;
    }

    /**
     * This method returns the get expression associated with the fetch
     * operation.
     * 
     * @return The get expression.
     */
    protected com.ibm.commerce.oagis9.datatypes.GetType getGet() {
        return iGetVerb;
    }

    
}