package jp.ac.osaka_u.sanken.sparql.plugin.compare;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

	
	public static List<String> readFileText(File file, String encode){
		List<String> ret = new ArrayList<String>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encode));
			
			String line;
			line = br.readLine();
			while (line != null){
				ret.add(line);
				line = br.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
	public static List<String> splitLine(String line, String separator){
		// ・""で囲まれていれば何があろうがワンセット
		// ・セパレーターで区切られたところで分割
		// ・""は削除する
		List<String> ret = new ArrayList<String>();
		StringBuilder sb = new StringBuilder();
		boolean literal = false;
		boolean sep = false;
		
		for (int i=0; i<line.length(); i++){
			String chr = line.substring(i, i+1);
			
			if (chr.equals("\"")){
				sep = false;
				literal = !literal;
			} else if (chr.equals(separator) && !literal){
				sep = true;
				ret.add(sb.toString());
				sb = new StringBuilder();
			} else {
				sep = false;
				sb.append(chr);
			}
		}
		if (sb.length() > 0 || sep){
			ret.add(sb.toString());
		}
		
		return ret;
	}
}
