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 com.hp.hpl.jena.util.iterator.ClosableIterator;
import java.util.*;

/**
 * 文字列の要素からなるリストの、それぞれの要素を
 * 結合して一つの文字列を作るビルトイン。
 * ビルトインの名前は'list2string'。第1引数にリスト、
 * 第2引数に変数を指定して使う。
 */
public class List2StringBuiltin extends BaseBuiltin {
    public String getName() {
        return "list2string";
    }

    public int getArgLength() {
        return 2;
    }

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

    public void headAction(Node[] args, int length, RuleContext context) {
        list2string(args,length,context);
    }

    void list2string(Node[] args,int length,RuleContext context) {
        String ret = list2stringR(args[0],context);
        BindingEnvironment env = context.getEnv();
        env.bind(args[1],Node.createLiteral(ret));
    }
    String list2stringR(Node n,RuleContext context) {
        String ret = "";
        Node first = Node.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
        Node rest = Node.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
        Node nil = Node.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
        ArrayList<Node> al = new ArrayList<Node>();
        Node tmpN = n;
        while (!tmpN.equals(nil)) {
            ClosableIterator ci = context.find(tmpN,first,null);
            Node e = ((Triple)ci.next()).getObject();
            al.add(e);
            ci = context.find(tmpN,rest,null);
            tmpN = ((Triple)ci.next()).getObject();
        }
        ret = ret + "(";
        Node nn[] = al.toArray(new Node[0]);
        for (int i=0;i<nn.length;i++) {
            if (nn[i].isBlank()) {
                ClosableIterator ci = context.find(nn[i],first,null);
                if (ci.hasNext()) {
                    ci = context.find(nn[i],rest,null);
                    if (ci.hasNext()) {
                        ret = ret + list2stringR(nn[i],context);
                        continue;
                    }
                }
            }
            String sTmp = nn[i].toString();
            if (sTmp.startsWith("\"") && sTmp.endsWith("\""))
                sTmp = sTmp.substring(1,sTmp.length()-1);
            ret = ret + sTmp+" ";
        }
        ret = ret + ") ";
        return ret;
    }
}
