/*
 * HtmlDecoder.java
 *
 * Created on 8 de febrero de 2005, 04:34 PM
 */

package com.fenalco.utilities.html;

import java.util.Hashtable;
import sun.misc.CharacterDecoder;
/**
 *
 * @author  Administrator
 */
public class HtmlDecoder {
    
    private static Hashtable tokens;
    /** Creates a new instance of HtmlDecoder */
    private HtmlDecoder() {
        
    }
 
     
    
    public static String decodeHtml(String text){
       String  htmlText = new String();
       HtmlDecoder.buildTokensTable();
       
       for(int i = 0 ; i < text.length(); i++){
           String token = "";
           char element = text.charAt(i);
           if( element == '&'){
                int j = text.indexOf( (int)';',i );
               token = text.substring(i, j+1 );
                i=j;
               
           }
           else{
                 token = element+"";
           }
            
           htmlText += HtmlDecoder.decodeToken( token );
       }
       return htmlText;
        
    }
    
    private static String decodeToken(String element){
        String htmlString = (String)HtmlDecoder.tokens.get( element);
        htmlString = (htmlString == null ? element+"":htmlString);
        return htmlString;
        
    }
    
    private static void buildTokensTable(){
        
        HtmlDecoder.tokens = new Hashtable();
        String[] strTokens = { " ", "“", "”", "—", "¡", "¨", "©",
                          "«", "®", "°", "±", "´", "¸", "»", 
                          "Á", "Ä", "É", "Ë", "Í", "Ï", "Ó",
                          "Ö", "Ú", "Ü", "á", "ä", "é", "ë",
                          "í", "ï", "ó", "ö", "ú", "ü" ,"ñ","Ñ"
                        };
        String[] keys = { "&nbsp;","&#8220;","&#8221;","&#8212;","&iexcl;","&uml;","&copy;",
                                "&laquo;","&reg;","&deg;","&plusmn;","&acute;","&cedil;","&raquo;",
                                "&Aacute;","&Auml;","&Eacute;","&Euml;","&Iacute;","&Iuml;","&Oacute;",
                                "&Ouml;","&Uacute;","&Uuml;","&aacute;","&auml;","&eacute;","&euml;",
                                "&iacute;","&iuml;","&oacute;","&ouml;","&uacute;","&uuml;","&ntilde;","&Ntilde;" 
                                };
        
        for(int i = 0 ; i < keys.length ; i++ ){
            tokens.put(keys[i], strTokens[i]);
        }
    }
    
    
}
