package jp.ac.do_johodai.j314.sw.je;

import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
import com.hp.hpl.jena.reasoner.rulesys.RuleContext;
import com.hp.hpl.jena.reasoner.rulesys.BindingEnvironment;

/**
 * 第1引数(整数)から第2引数(整数)の間の乱数を第三引数に代入する。
 * ビルトインの名前は'rand_int'。
 */
public class RandIntBuiltin extends BaseBuiltin {
    public String getName() {
        return "rand_int";
    }

    public int getArgLength() {
        return 3;
    }

    public boolean bodyCall(Node[] args, int length, RuleContext context) {
        if (length != 3)
            return false;
        bindRandInt(args,length,context);
        return true;
    }

    public void headAction(Node[] args, int length, RuleContext context) {
        bindRandInt(args,length,context);
    }
    void bindRandInt(Node[] args, int length, RuleContext context) {
        String n1s = ((Node_Literal)args[0]).getLiteralLexicalForm();
        String n2s = ((Node_Literal)args[1]).getLiteralLexicalForm();
        int n1 = Integer.parseInt(n1s);
        int n2 = Integer.parseInt(n2s);
        java.util.Random r = new java.util.Random();
        int nn = n1 + r.nextInt(Math.abs(n2-n1)+1);
        Node n = Node.create(""+nn);
        BindingEnvironment env = context.getEnv();
        env.bind(args[2],n);
    }
}
