/**
 * @(#)RHTMLDocument.java
 * Copyright 2001 Nomura Research Institute, LTD. All rights reserved.
 * RID-3 : RID HTML Document
 * @author  Intelligent Technology Inc.
 * @version 1.00 2001/10/01-2001/03/25
 * @see HTMLDocument
 */

package	jp.co.nri.rid.analyzer;

import	javax.swing.text.*;
import	javax.swing.text.html.*;
import	java.util.*;
import	jp.co.nri.rid.xml.elementBooster;

/**
 * HTMLDocumentにareaタグを取得する機能を付加した。
 */

public class RHTMLDocument extends HTMLDocument{
	public	Vector			areas	= new Vector();
	private elementBooster	xmlelem;
	private HashMap			list;
	private int				depth = 0;
	
	/**
	 * RID Document(Site.XML Resource.XML Document.XML)をAnalizeする。
	 * @since	1.00
	 */
	public RHTMLDocument(HashMap list, elementBooster xmlelem){
		this.xmlelem	= xmlelem;
		this.list		= list;
	}
	
	/**
	 * スーパークラスHTMLDocumentのメソッドをオーバーライド。
	 * HTMLEditorKitにより呼び出されareaタグを収集する機能を付加したHTMLReaderを返す。
	 * @since	1.00
	 */
    public HTMLEditorKit.ParserCallback getReader(int pos){ return new RHTMLReader(); }
	
/**
 * areaタグを取得する機能を付加したHTMLReader。
 * @see HTMLDocument.HTMLReader
 */
	public class RHTMLReader extends HTMLReader{
		public RHTMLReader(){ super(0); }
		
		public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos){
//System.err.println("<"+t+" "+a+"/>");
			String name = t.toString().toLowerCase();
			
			if( null != list.get(name) ){
				getAttributes(xmlelem.add(name), a.copyAttributes());
			}
			
			if("area".equalsIgnoreCase(name))	areas.add(a.copyAttributes());
			
			try{ super.handleSimpleTag(t,a,pos); }
			catch(NullPointerException e){}
		}
		
		public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos){
//System.err.println("<"+t+" "+a+">");
			String name = t.toString().toLowerCase();
			
			if( null != list.get(name) ){
				xmlelem = xmlelem.add(name);
				depth++;
				getAttributes(xmlelem, a.copyAttributes());
			}
			
			super.handleStartTag(t,a,pos);
		}
		
		public void handleEndTag(HTML.Tag t, int pos){
//System.err.println("</"+t+">");
			if( xmlelem.tagname().equalsIgnoreCase(t.toString()) && (0 < depth) ){
				elementBooster elm = xmlelem.parent();
				if(null != elm)	xmlelem = elm;
				depth--;
			}
			
			super.handleEndTag(t,pos);
		}
		
		private void getAttributes(elementBooster elm, AttributeSet aset){
			Enumeration enum = aset.getAttributeNames();
			while(enum.hasMoreElements()){
				Object key		=	enum.nextElement();
				String keystr	=	key.toString();
				Object value	=	aset.getAttribute(key);
				
				if(value instanceof String)				elm.attribute(key.toString(), (String)value);
				else if(value instanceof AttributeSet)	getAttributes(elm.add(key.toString()), (AttributeSet)value);
				else{
					elementBooster e = elm.add(key.toString());
					if(null != value)	e.text(value.toString());
				}
			}
		}
	}
}
