package imseProc.jotter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map.Entry;

import otherSupport.SettingsManager;

public class JotterNotesDB {
	
	private static JotterNotesDB instance;
	
	public static JotterNotesDB getInstance() {
		if(instance == null)
			instance = new JotterNotesDB();
		return instance;
	}
	 
	private String path;
	
	private HashMap<Integer, String> notes;
	
	public JotterNotesDB() {
		this.path = SettingsManager.defaultGlobal().getPathProperty("imseProc.jotter.path");
		loadNotes();
	}
	
	public void setText(int pulse, String text){
		if(text == null){
			notes.put(pulse, null);
		}else	
			// newlines --> '\n' in file
			// '\' --> '\\' in file
			notes.put(pulse, text.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\n", "\\\\n"));
		saveNotes();
	}
	
	public String getText(int pulse){
		String txt = notes.get(pulse);
		// '\n' in file --> newline
		// '\\' in file --> '\'
		return (txt == null) ? null :  txt.replaceAll("\\\\n", "\n").replaceAll("\\\\\\\\", "\\\\");
	}
	

	private void loadNotes() {
		try {
			notes = new HashMap<Integer, String>();
			BufferedReader br = new BufferedReader(new FileReader(path + "/notes.txt"));
			
			do{
				String line;
					line = br.readLine();
				
				if(line == null)
					break;
				String parts[] = line.split("\t", 2);
				int pulse = Integer.parseInt(parts[0]);
				notes.put(pulse, parts[1]);
				
			}while(true);
			
			br.close();
		} catch (IOException e) {
			System.err.println("Error loading notes.txt:");
			e.printStackTrace();
		}
	}
	
	private void saveNotes() {
		try {
			PrintWriter pw = new PrintWriter(path + "/notes.txt");
		
			for(Entry<Integer, String> entry : notes.entrySet()){
				pw.println(entry.getKey() + "\t" + entry.getValue());
			}
			pw.close();
		} catch (IOException e) {
			System.err.println("Error writing notes.txt:");
			e.printStackTrace();
		}
	}

	public String getPath() { return path;	}
}
