package commons.application.ctx;
import basics.utl.Empty;
import basics.utl.SUtl;
public class Contract
{

private String   missingKey = "";
private String[] precond    = null;
private String[] postcond   = null;

public Contract(String precond, String postcond)
{
   if (!Empty.is(precond))
      this.precond = SUtl.split(precond);
   if (!Empty.is(postcond))
      this.postcond = SUtl.split(postcond);
}

public Contract(String[] precond, String[] postcond)
{
   this.precond = precond;
   this.postcond = postcond;
}

public String[] getPreconditions ()
{
   return precond;
}

/***************************************************************************************************
 * check all preconditions: keys must exist and values != null
 * @param ctx that should contain the keys
 * @return ok or false
 */
public boolean preconditionsFullfilled (Context ctx)
{
   if (precond != null)
   {
      for (int i = 0; i < precond.length; i++)
      {
         String k = precond[i];
         if (k.trim().length() == 0)
            continue;
         if (!ctx.containsKey(k))
         {
            missingKey = k;
            return false;
         }
         Object v = ctx.getr(k);
         if (v == null)
         {
            missingKey = k;
            return false;
         }
         else if (Empty.is(v))
         {
            missingKey = k;
            return false;
         }
      }
   }
   return true;
}

/***************************************************************************************************
 * check all postconditions: keys must exist and values != null
 * @param ctx that should contain the keys
 * @return ok or false
 */
public boolean postconditionsFullfilled (Context ctx)
{
   if (postcond != null)
   {
      for (int i = 0; i < postcond.length; i++)
      {
         String k = postcond[i];
         if (k.trim().length() == 0)
            continue;
         if (!ctx.containsKey(k))
         {
            missingKey = k;
            return false;
         }
         Object v = ctx.getr(k);
         if (v == null)
         {
            missingKey = k;
            return false;
         }
      }
   }
   return true;
}

/**
 * tell me which key was missing
 * @return key
 */
public String getKeyThatBrokeTheContract ()
{
   return missingKey;
}

public String toString ()
{
   StringBuilder s = new StringBuilder();
   return s.toString();
}
}
