/*
 * Licensed Materials - Property of Rogue Wave Software, Inc. 
 * © Copyright Rogue Wave Software, Inc. 2014, 2015 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */
package datasource.explorer;

import ilog.cpl.datasource.IlpDataSource;
import ilog.cpl.datasource.structure.IlpChild;
import ilog.cpl.model.IlpObject;
import ilog.cpl.util.IlpFilter;

/**
 * Filter which specifies the objects that will be displayed
 * in the Table Component.
 */
public class OriginFilter implements IlpFilter {
  IlpObject origin;
  IlpDataSource dataSource;
  boolean recurse;

  /**
   * Filter that returns true for all objects contained under the given origin.
   * If the <code>recurse</code> parameter is true, children recursively
   * contained are also accepted.
   */
  public OriginFilter(IlpDataSource dataSource,
                      IlpObject origin,
                      boolean recurse) {
    this.dataSource = dataSource;
    this.origin = origin;
    this.recurse = recurse;
  }

  public IlpObject getOrigin(){return this.origin;}

  public boolean isChildOfOrigin(IlpObject object) {
    if (object==origin)
      return false;

    // Null origin with recursion allows all objects,
    // and that is not what we want
    if ((origin==null) && recurse)
      return false;

    IlpChild childItf = dataSource.getChildInterface(object);
    // if no child interface, this object only qualifies if there is no origin
    if (childItf==null)
      return (origin==null);
    IlpObject parent = dataSource.getObject(childItf.getParent(object));
    if (parent==origin)
      return true;
    else
      return (recurse && isChildOfOrigin(parent));
  }

  /**
   * Accept only objects that are contained under the origin
   */
  public boolean accept (Object object) {
    return isChildOfOrigin((IlpObject)object);
  }
}