package com.approximatrix.draco.io;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.HTMLElements;
import au.id.jericho.lib.html.Segment;
import au.id.jericho.lib.html.Source;

public class HTMLImportExport {
	
	public static String ConvertHTMLToTextTable(String html) {
		try {
			StringBuffer ret = new StringBuffer();
			
			Source src = new Source(new StringReader(html));
			
			Element ele = src.findNextElement(0, HTMLElements.TABLE);
			List rows = ele.findAllElements(HTMLElements.TR);
			
			for(Object row : rows) {
				if(row instanceof Segment) {
					
					List cols = ((Segment)row).findAllElements(HTMLElements.TD);
					for(Object col : cols) {
						if(col instanceof Segment) {
							String toAdd = CleanText(((Segment)col).getTextExtractor().toString());
							ret.append(toAdd);
							ret.append('\t');
						}	
					}
					ret.deleteCharAt(ret.length()-1);
				}
				ret.append('\n');
			}
			return ret.toString();
		} catch(IOException ioe) {
			return null;
		} catch(NullPointerException npe) {
			return null;
		}
	}

	/** Removes all whitespace from a string
	 * 
	 * @param input the string to clean
	 * @return a string where all whitespace has been replaced with _
	 */
	private static String CleanText(String input) {
		// Replace all whitespace with underscore
	    return new String(input).replaceAll("\\s", "_");
	}
	
}
