/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.aspects.dbc.condition;

import java.util.Iterator;

import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aspects.dbc.DesignByContractAspect;

import bsh.EvalError;
import bsh.Interpreter;

/**
 *
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.1.8.3 $
 */
public class InvariantCondition extends Condition
{
   public InvariantCondition(Class clazz, String condExpr, boolean isStatic)
   {
      super(condExpr, clazz, isStatic);
   }

   public void evaluateCondition(Invocation inv, boolean staticCall, boolean constructor, Object ret)
   {
      try
      {
         if (DesignByContractAspect.verbose) System.out.println("[dbc] Evaluate condition : '" + originalExpr + "' for class: " + clazz);
         
         if (!isStatic && staticCall)
         {
            System.out.println("[dbc] Ignoring non-static invariant for static call");
            return;
         }
   
         Interpreter interpreter = new Interpreter();
         Object target = (constructor) ? ret : getTarget(inv, staticCall);
         
         for (Iterator it = parameterLookup.keySet().iterator() ; it.hasNext() ; )
         {
            String bsname = (String)it.next();
            String originalname = (String)parameterLookup.get(bsname); 
            if (originalname.equals(Condition.TARGET))
            {
               interpreter.set(bsname, target);
               if (DesignByContractAspect.verbose) System.out.println("[dbc] Setting $" + originalname + " to " + target +" (type: " + target.getClass().getName() + ")");
            }
            else
            {
               System.out.println("INVARIANT CONDITION BROKEN: "+ originalExpr + " - " + clazz);
               throw new RuntimeException("Invalid marker '" + originalname + "' in expression: " + originalExpr);
            }
         }
         
         Boolean eval = (Boolean)interpreter.eval(condExpr);
   
         if (!eval.booleanValue())
         {
            throw new RuntimeException("Invariant condition " + originalExpr + " was broken " + "for class: " + clazz);
         }
      }
      catch (EvalError e)
      {
         throw new RuntimeException("There was an error in the expression: " + originalExpr, e);
      }
   }
   
   public boolean equals(Object o)
   {
      if (o instanceof InvariantCondition)
      {
         return super.equals(o);
      }
      return false;
   }
   
}
