/*
 2000-2004 eBay Inc. All rights reserved.

eBay, eBay API, and eBay SDK are trademarks of eBay Inc.

Sample Source Code License
The material below is sample source code in the form of example
applications and code fragments (both in the source code files and
documentation provided hereunder), and may include a tutorial
application (collectively, "Sample Source Code" or "SSC").  YOUR
RECEIPT AND USE OF THE SSC IS CONTINGENT UPON THE TERMS AND CONDITIONS
SET FORTH BELOW.

License. Subject to the terms and restrictions set forth herein, eBay
grants you a non-exclusive, non-transferable, non-sublicensable,
royalty-free license to download and use the SSC solely to create and
distribute derivative works ("Derivative Works") which are designed to
assist your end users to efficiently interact with the eBay Site
(e.g., a listing application) (the "License").  Except as otherwise
expressly stated below, you are not permitted to sell, lease, rent,
copy, distribute or sublicense the SSC, or derivative copies thereof,
or to use it in a time-sharing arrangement or in any other
unauthorized manner. This License does not grant you any rights to
patents, copyrights, trade secrets, trademarks, or any other rights in
respect to the SSC.

Redistribution. You may not use the SSC in any manner that is not
expressly authorized under this License. Without limiting the
foregoing, you may redistribute, use and create Derivative Works in
source and binary forms, subject to the following conditions:
  1. Redistributions of SSC must retain this list of conditions and
     the copyright notice and disclaimer noted below.
  2. Redistributions in binary form must reproduce the copyright
     notice, this list of conditions and the disclaimer in the
     documentation and/or other materials provided with the
     distribution.
  3. Redistribution Conditions:
      Neither the name of eBay Inc. nor the names of its contributors
       may be used to endorse or promote products derived from this
       software or materials without specific prior written
       permission.
      Disclaimer. "THIS SOFTWARE AND ANY RELATED MATERIALS ARE
       PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
       ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
       COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
       INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
       DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
       LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
       THE USE OF THIS SOFTWARE, AND/OR ANY RELATED MATERIALS, EVEN IF
       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
      Copyright Notice: "Copyright (c) 2003, eBay Inc.
                          All rights reserved."

*/

package com.ebay.sdk.attributes;

import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Enumeration;
import com.ebay.sdk.attributes.model.*;
import com.ebay.sdk.SdkException;
import com.ebay.soap.eBLBaseComponents.*;
import com.ebay.sdk.attributes.model.*;

/**
 * Parser for post data of product finder HTML.
 * <p>Title: AttributesLib for Java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: eBay Inc.</p>
 * @author Weijun Li
 * @version 1.0
 */
abstract class ProductFinderParamParser {
  static final String PFID = "pfid";
  static final String A = "a";

  public static final String US = "_";
  public static final String USD = "_d";
  public static final String USM = "_m";
  public static final String USY = "_y";

  /**
   * Gets groupKey to PFID map.
   * @param request Map
   * @return Map
   */
  static java.util.Map getPFIDList(java.util.Map request)
  {
    Hashtable pfids = new Hashtable();

    Object[] keys = request.keySet().toArray();
    for(int i = 0; i < keys.length; i++ )
    {
      String key = (String)keys[i];
      if( !key.startsWith(PFID) )
        continue;

      String val = ((String[])request.get(key))[0];
      String skey = key.substring(PFID.length());
      if( skey.length() == 0 || skey.charAt(0) == '_' )
        pfids.put(skey, val);
    }

    return pfids;
  }

  private static Object findValueByStringKey(java.util.Map map, String strKey)
  {
    Object[] keys = map.keySet().toArray();
    for(int i = 0; i < keys.length; i++ )
    {
      String key = (String)keys[i];
      if( key.equals(strKey) )
      {
        return map.get(key);
      }
    }

    return null;
  }

  private static SearchAttributeSet findAttributeSetByPFID(SearchAttributeSet[] sets, int pfid)
  {
    for(int i = 0; i < sets.length; i++ )
    {
      if( pfid == sets[i].getProductFinderID() )
        return sets[i];
    }
    return null;
  }

  /**
   *
   * @param request Map
   * @throws SdkException
   * @throws Exception
   * @return SearchAttributeSet[]
   */
  static SearchAttributeSet[] parseProductFinderPostData(java.util.Map request)
    throws SdkException, Exception
  {
    int i;
    java.util.Map gkey_pfid = getPFIDList(request);
    if( gkey_pfid.size() == 0 )
      throw new SdkException("No product finder post data were found.");

    Object[] rgPFID = gkey_pfid.values().toArray();

    //
    SearchAttributeSet[] sets = new SearchAttributeSet[gkey_pfid.size()];
    for( i = 0; i < sets.length; i++ )
    {
      sets[i] = new SearchAttributeSet();
      sets[i].setProductFinderID(Integer.parseInt((String)rgPFID[i]));
    }

    //
    Object[] keys = request.keySet().toArray();
    for(i = 0; i < keys.length; i++ )
    {
      String key = (String) keys[i];

      if (!key.startsWith(A))
        continue;

      String skey = key.substring(A.length());
      String aid, groupKey;
      int us_idx = skey.indexOf(US);
      if( us_idx != -1 )
      {
        aid = skey.substring(0, us_idx);
        groupKey = skey.substring(us_idx);
      }
      else
      {
        aid = skey;
        groupKey = "";
      }

      String valStr = ((String[])request.get(key))[0];

      Object objPFID = findValueByStringKey(gkey_pfid, groupKey);
      if( objPFID == null )
        throw new SdkException("Invalid group key.");

      SearchAttributeSet set = findAttributeSetByPFID(sets, Integer.parseInt((String)objPFID));
      SearchAttribute attr = new SearchAttribute();
      attr.setAttributeID(Integer.parseInt(aid));
      Value val = new Value();
      val.setValueID(new Integer(valStr));
      attr.addValue(val);
      set.add(attr);
    }

    return sets;
  }
}
