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;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 第1引数(DateTime)をlongに変換して第2引数(long)の変数に
 * 代入する。
 * ビルトインの名前は'datetime2long'。
 */
public class DateTime2LongBuiltin extends BaseBuiltin {
    public String getName() {
        return "datetime2long";
    }

    public int getArgLength() {
        return 2;
    }

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

    public void headAction(Node[] args, int length, RuleContext context) {
        datetime2long(args,length,context);
    }
    void datetime2long(Node[] args, int length, RuleContext context) {
        String s = ((Node_Literal)args[0]).getLiteralLexicalForm();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(s);
        } catch (Exception e) {
            e.printStackTrace();
            date = new Date(0l);
        }
        long l = date.getTime();
        Node n = Node.create(""+l);
        BindingEnvironment env = context.getEnv();
        env.bind(args[1],n);
    }
}
