package jp.ac.osaka_u.sanken.sparql;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import com.hp.hpl.jena.rdf.model.RDFNode;

/**
 * セパレータによって区切られた形でデータをエクスポートするためのクラス
 * @author kato
 *
 */
public class SeparatedValuesExporter {
	
	private String separator;
	private List<Map<String, RDFNode>> data;
	
	public SeparatedValuesExporter(String separator, List<Map<String, RDFNode>> data){
		this.separator = separator;
		this.data = data;
	}

	public boolean export(File file) throws IOException{
		return export(new FileOutputStream(file));
	}

	public boolean export(OutputStream stream) throws IOException{
		
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(stream));

		if (!outputHeader(pw, data.get(0))){
			pw.flush();
			pw.close();
			return false;
		}
		
		for (Map<String, RDFNode> datum : data){
			outputContent(pw, datum);
		}
		pw.flush();
		pw.close();
		
		return false;
	}
	
	private boolean outputHeader(PrintWriter stream, Map<String, RDFNode> columns){
		StringBuilder sb = new StringBuilder();
		
		int i = 0;
		for (String key : columns.keySet()){
			sb.append(key);
			if (++i != columns.keySet().size()){
				sb.append(getSeparator());
			}
		}
		
		outputLine(stream, sb.toString());
		
		return true;
	}

	private boolean outputContent(PrintWriter stream, Map<String, RDFNode> row){
		StringBuilder sb = new StringBuilder();
		
		int i = 0;
		for (String key : row.keySet()){
			sb.append(row.get(key));
			if (++i != row.keySet().size()){
				sb.append(getSeparator());
			}
		}
		
		outputLine(stream, sb.toString());
		
		return true;
	}

	private String getSeparator(){
		return this.separator;
	}
	
	private void outputLine(PrintWriter stream, String line){
		stream.println(line);
	}
	
}
