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

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

public abstract class AbstractPropagtionRule implements PropagationRule
{
   public void changeState(Node node, long itemId, long state)
   {
      StateItem target = node.findStateItem(itemId);
      if (target == null)
      {
         System.out.println("[Error] StateItem not found. : " + node + ":"
                 + itemId);
         return;
      }

      if (StateItem.STATE_CHANGED == target.setState(state))
      {
         summaryUpperPropagate(node);
      }
   }

   protected void upperPropagate(Node node)
   {
      Node parentNode = (Node) node.getParentNode();
      if (parentNode != null)
      {
         PropagationRule parentRule = parentNode.getPropagationRule();
         parentRule.summaryUpperPropagate(parentNode);
      }
   }

   protected boolean isClear(StateItem item)
   {
      long state = item.getState();
      if ((state % 10) == 0)
      {
         return true;
      } else
      {
         return false;
      }
   }

   protected long getSeverity(StateItem item)
   {
      long state = item.getState();
      long severity = 0;
      if (isSummaryItem(item))
      {
         severity = state % 1000;
      } else
      {
         severity = (state % 1000) / 10;
      }

      return severity;
   }

   protected boolean isSummaryItem(StateItem item)
   {
      long state = item.getState();
      long summaryDigit = (state / 1000) % 10;

      if (summaryDigit == 2)
      {
         return true;
      } else
      {
         return false;
      }
   }

   protected long updateMaxSeverity(long maxSeverity, StateItem stateItem)
   {
      if (!isClear(stateItem))
      {
         long severity = getSeverity(stateItem);
         if (severity > maxSeverity)
         {
            maxSeverity = severity;
         }
      }

      return maxSeverity;
   }
}
