package com.yuji.ec.utility;

import java.io.IOException;
import java.io.StringReader;

import org.ccil.cowan.tagsoup.Parser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import com.yuji.ec.common.CommonUtil;

public class HtmlParser implements ContentHandler {
	// http://java.sun.com/javase/ja/6/docs/ja/api/index.html?org/xml/sax/ContentHandler.html
	// http://www35.atwiki.jp/nikoban/pages/23.html
	//private final static String NL = System.getProperty("line.separator");
	private StringBuffer sb = null;
	
	public boolean parse(String str){
		boolean result = false;
		try {
        	sb = new StringBuffer();
        	
    		StringReader sr = new StringReader(str);
    		InputSource is = new InputSource(sr);
    		
    		Parser parser = new Parser();
            parser.setContentHandler(this);

            parser.setFeature(Parser.namespacesFeature, false);
            parser.parse(is);

            result = true;
		} catch (SAXNotRecognizedException e) {
			Debug.d(this, null, e);
		} catch (SAXNotSupportedException e) {
			Debug.d(this, null, e);
		} catch (IOException e) {
			Debug.d(this, null, e);
		} catch (SAXException e) {
			Debug.d(this, null, e);
		}
		return result;
	}

	public String getText(){
		return (sb != null)? sb.toString() : null;
	}
	
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (sb.length() > 0){
			//sb.append(NL);
		}
		String str = new String(ch, start, length);
		str = CommonUtil.replaceString(str, "\\n", "");
		sb.append(str);
	}

	public void endDocument() throws SAXException {
		
	}

	public void endElement(String uri, String localName, String qName) 
			throws SAXException {
		
	}

	public void endPrefixMapping(String prefix)  throws SAXException {
		
	}

	public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
			throws SAXException {
		
	}

	public void processingInstruction(String arg0, String arg1)
			throws SAXException {
		
	}

	public void setDocumentLocator(Locator arg0) {
		
	}

	public void skippedEntity(String arg0) throws SAXException {
		
	}

	public void startDocument() throws SAXException {
		
	}

	public void startElement(String arg0, String arg1, String arg2,
			Attributes arg3) throws SAXException {
		
	}

	public void startPrefixMapping(String arg0, String arg1)
			throws SAXException {
		
	}
}
