/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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", "_");
	}
	
}
