/*
 * 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 monitoring.web.model.integration.filters;

import monitoring.shared.MonitoringConstants;
import monitoring.web.utils.WebUtils;
import ilog.cpl.model.IlpClass;
import ilog.cpl.model.IlpClassManager;
import ilog.tgo.model.IltAlarm;
import ilog.tgo.model.IltNetworkElement;

/**
 * Filters out IltAlarm objects whose managed object is not of a given 
 * type. So it keeps only objects that are IltAlarm instances whose managed 
 * object is of the type specified in this class' "type" property.
 */
public class AlarmOnTypeFilter extends TypeFilter {

  private IlpClassManager classManager;

  public boolean accept(Object object) {

    boolean accept = false;

    if (object instanceof IltAlarm) {

      //No type, means no filtering 
      if (getType() == null) {
        return true;
      }

      //We have an alarm
      IltAlarm alarm = (IltAlarm) object;

      //Find its target managed object class name 
      String managedInstanceClassName = getManagedInstanceClassName(alarm);

      IlpClass managedInstanceType = getClassManager().getClass(
          managedInstanceClassName);

      //If we have it, apply the test to its class
      if (managedInstanceType != null) {
        accept = getType().isAssignableFrom(managedInstanceType);
      }
    }

    return accept;
  }

  private IlpClassManager getClassManager() {
    if (classManager == null) {
      classManager = WebUtils.getTGOContext().getClassManager();
    }
    return classManager;
  }

  private String getManagedInstanceClassName(IltAlarm alarm) {

    String className = alarm.getAttributeValue(
        IltAlarm.ManagedObjectClassAttribute).toString();

    //See monitoring.generator.internal.AlarmGenerator.getMOC for more info on why this is 
    //needed
    if ((className != null)
        && (className
            .indexOf(MonitoringConstants.MANAGED_ELEMENT_CLASS_NAME + "/")) > -1) {
      className = IltNetworkElement.class.getName();
    }
    return className;
  }
}