package org.jboss.cache.pojo.test.propagation.impl;

import org.jboss.cache.pojo.test.propagation.Node;
import org.jboss.cache.pojo.test.propagation.StateItem;

import java.util.List;

public class ORSummaryRule extends AbstractPropagtionRule
{
   private static final String RULE_NAME = "OR-Rule";

   public void summaryUpperPropagate(Node node)
   {
      long maxSeverity = 0;

      List<StateItem> stateItems = node.getStateItems();
      int size = stateItems.size();
      for (int idx = 0; idx < size; idx++)
      {
         StateItem stateItem = (StateItem) stateItems.get(idx);

         maxSeverity = updateMaxSeverity(maxSeverity, stateItem);
      }

      List<Node> childNodes = node.getChildren();
      size = childNodes.size();
      for (int idx = 0; idx < size; idx++)
      {
         Node child = (Node) childNodes.get(idx);
         StateItem childSummary = child.getSummaryStateItem();

         maxSeverity = updateMaxSeverity(maxSeverity, childSummary);
      }

      long summaryState = STATE_CLEAR + maxSeverity;
      StateItem summaryItem = node.getSummaryStateItem();
      boolean isSummaryChanged = summaryItem.setState(summaryState);

      if (StateItem.STATE_CHANGED == isSummaryChanged)
      {
         upperPropagate(node);
      }
   }

   public String toString()
   {
      return RULE_NAME;
   }
}
