package exp.twostep;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;


public class DataRepresent {
	
	public static final String otherTextDelimiter = "\t";
	public static final String mapItemDelimiter = "|||";
	
	HashMap<String, double[]> content;
	HashMap<String, String> textMapper;
	HashMap<String, String> reverseTextMapper;
	ArrayList<String[]> rowHeaders;
	
	public DataRepresent(String file, int rowHeader, int colHeader, String delimiter) throws Exception{
		
		//colHeader/rowHeader should be no less than 1
		System.out.println(file);
		content = new HashMap<String, double[]>();
		textMapper = new HashMap<String, String>();
		reverseTextMapper = new HashMap<String, String>();		
		rowHeaders = new ArrayList<String[]>();
		
		try (FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr)){
			String line = "";
			for (int i = 0; i < rowHeader; i++){
				line = br.readLine();
				if (line != null && line.length() > 2){
					rowHeaders.add(line.split(delimiter));
				}else{
					throw new Exception("Bad file: header is null");
				}
			}
			int uu = 0;
			while ((line = br.readLine()) != null){
				if ((uu++)%1000==0)
					System.out.println(file + " line:" + (uu));
				String[] spl = line.split(delimiter);
				String key = spl[0];
				double[] value = new double[spl.length - colHeader];
				String otherKey = "";
				for (int i = 1; i < colHeader; i++){
					otherKey += spl[i];
				}
				for (int i = colHeader; i < spl.length; i++){
					value[i - colHeader] = Double.parseDouble(spl[i]);
				}
				if (!content.containsKey(key)){
					content.put(key, value); //for met, duplicate items share the same data. so only one is saved.
				}
				
				if (!content.containsKey(textMapper)){
					textMapper.put(key, otherKey);
				}else{
					textMapper.replace(key, textMapper.get(key) + otherTextDelimiter + otherKey);
				}
				//reversed version will face the problem that some keys have multiple values
				if (reverseTextMapper.containsKey(otherKey)){
					reverseTextMapper.replace(otherKey, reverseTextMapper.get(otherKey) + otherTextDelimiter + key);
				}else{
					reverseTextMapper.put(otherKey, key);
				}	
			}
			
		}catch (FileNotFoundException ffe){
			ffe.printStackTrace();
		}catch (IOException ioe){
			ioe.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
