/* $Id: LinkChecker.java 125 2011-03-09 09:49:51Z ohura $ */
package smart_gs.connection;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;

import smart_gs.util.HrefChecker;

public class LinkChecker {
	protected HashMap<String, Integer> linkMap = new HashMap<String, Integer>();
	
	public void parse(String source){
		try{
			ParserDelegator pd = new ParserDelegator();
			LinkCheckerCallback cb = new LinkCheckerCallback();
			BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(source.getBytes()),"UTF-8"));
			pd.parse(reader, cb, true);
		}catch(Exception e){
			
		}
	}
	public HashMap<String, Integer> getLinkMap(){
		return linkMap;
	}
	
	class LinkCheckerCallback extends HTMLEditorKit.ParserCallback {
		public void handleStartTag(HTML.Tag tag, MutableAttributeSet attr, int pos){
			if (tag.equals(HTML.Tag.A)) {
				String ret = (String)attr.getAttribute(HTML.Attribute.HREF);
				try{
					int checkid = HrefChecker.check(ret);
					if(checkid != -1){
						linkMap.put(ret,new Integer(checkid));
					}
				}catch(NumberFormatException e){
					e.printStackTrace();
				}
			}
		}
	}

}
