/**
 * Created on Aug 16, 2007, 10:09:21 PM Copyright Ning Zhao. All rights
 * reserved.
 */
package quiz;

import java.io.InputStreamReader;
import java.io.Reader;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;

/**
 * 
 * @author ningning
 * @version $Id$
 */
public class Main {
  public Main() {}
  
  public static void main(String[] args) throws Exception {
    
    try {
      
      // load up the rulebase
      long start = System.currentTimeMillis();
      RuleBase ruleBase = readRule();
      WorkingMemory workingMemory = ruleBase.newStatefulSession();
      
      // go !
      long setup = System.currentTimeMillis();
      //System.out.println("Start time: " + start);
      for (int i = 1; i <= 36; i++) {
        // this is just to limit the number of assertions
        if ((36 % i) == 0) workingMemory.insert(new Son(i));
      }
      
      workingMemory.fireAllRules();
      long end = System.currentTimeMillis();
      
      long solvingTime = end - setup;
      long setupTime = setup - start;
      System.out.println("Rule base setup time: " + setupTime + " ms");
      System.out.println("Problem-solving time: " + solvingTime + " ms");
      
    } catch (Throwable t) {
      t.printStackTrace();
    }
    
    // execute
  }
  
  /**
   * Please note that this is the "low level" rule assembly API.
   */
  private static RuleBase readRule() throws Exception {
    // read in the source
    Reader source = new InputStreamReader(Main.class
        .getResourceAsStream("/finage.drl"));
    
    // optionally read in the DSL (if you are using it).
    // Reader dsl = new InputStreamReader(
    // DroolsTest.class.getResourceAsStream( "/mylang.dsl" ) );
    
    // Use package builder to build up a rule package.
    // An alternative lower level class called "DrlParser" can also be
    // used...
    
    PackageBuilder builder = new PackageBuilder();
    
    // this wil parse and compile in one step
    // NOTE: There are 2 methods here, the one argument one is for
    // normal DRL.
    builder.addPackageFromDrl(source);
    
    // Use the following instead of above if you are using a DSL:
    // builder.addPackageFromDrl( source, dsl );
    
    // get the compiled package (which is serializable)
    Package pkg = builder.getPackage();
    
    // add the package to a rulebase (deploy the rule package).
    RuleBase ruleBase = RuleBaseFactory.newRuleBase();
    ruleBase.addPackage(pkg);
    return ruleBase;
  }
}
