package com.horstmann.labrat;


import java.util.Scanner;
import java.util.regex.Pattern;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.condition.Condition;

public class AsExpectedCondition implements Condition {
    private String value;
    private double tolerance = 1.0E-6;

    // The setter for the "value" attribute
    public void setValue(String value) {
        this.value = value;
    }
    
    public void setTolerance(double tolerance)
    {
       this.tolerance = tolerance;
    }
    
    // This method evaluates the condition
    public boolean eval() {
        if (value == null) {
            throw new BuildException("value attribute is not set");
        }
        
        Scanner in = new Scanner(value);
        while (in.hasNextLine()) {
           String actual = in.nextLine();
           if (!in.hasNextLine())
              return false;
           String expected = in.nextLine();
           if (!(getPrefix(expected).equals("expected") 
              && match(getSuffix(actual), getSuffix(expected))))
              return false;
        }
        return true;        
    }
    
    private static String getPrefix(String s) {
       int n = s.indexOf(':');
       if (n == -1) return "";
       else return s.substring(0, n).toLowerCase();
    }
    
    private static String getSuffix(String s) {
       int n = s.indexOf(':');
       if (n == -1) return s.trim().toLowerCase();
       else return s.substring(n + 1).trim().toLowerCase();
    }
    
    private boolean match(String a, String b) {       
       if (a.equals(b)) return true;
       try
       {
          double x = Double.parseDouble(a);
          double y = Double.parseDouble(b);
          if (Math.abs(x - y) < tolerance) 
             return true;
       }
       catch (NumberFormatException ex)
       {
          // at least one of them isn't a number
       }
       return false;
    }
}

