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

import java.util.ArrayList;

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.util.iterator.ClosableIterator;

/**
 * 第1引数に与えられたRDFリストを標準出力に
 * 表示する。
 */
public class PrintListBuiltin extends BaseBuiltin {
    public String getName() {
        return "print_list";
    }

    public int getArgLength() {
        return 1;
    }

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

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

    void printList(Node[] args,int length,RuleContext context) {
        printListR(args[0],context);
        System.out.println();
    }
    void printListR(Node n,RuleContext context) {
        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();
        }
        System.out.print("(");
        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()) {
                        printListR(nn[i],context);
                        continue;
                    }
                }
            }
            System.out.print(nn[i].toString()+" ");
        }
        System.out.print(") ");
    }
}
