package org.maachang.proxy.engine.mobile.emoji ;

import org.maachang.proxy.engine.net.http.HttpParams;
import org.maachang.util.HttpdUtil;

/**
 * 絵文字用URLエンコード.
 * 
 * @version 2007/10/18
 * @author masahito suzuki
 * @since MaachangProxy 1.00
 */
public class EmojiEncode {
    /**
     * 指定パラメータ内容を指定charsetで変換.
     */
    public static final String convertBodyByCharset( String body,String charset )
        throws Exception {
        if( body == null || ( body = body.trim() ).length() <= 0 ) {
            return null ;
        }
        HttpParams params = new HttpParams() ;
        HttpdUtil.convertQueryByParams( params,body,charset ) ;
        StringBuilder buf = new StringBuilder() ;
        String[] keys = params.getKeys() ;
        if( keys != null ) {
            int len = keys.length ;
            int cnt = 0 ;
            for( int i = 0 ; i < len ; i ++ ) {
                if( cnt != 0 ) {
                    buf.append( "&" ) ;
                }
                int lenJ = params.size( keys[ i ] ) ;
                for( int j = 0 ; j < lenJ ; j ++ ) {
                    if( cnt != 0 ) {
                        buf.append( "&" ) ;
                    }
                    String v = ( String )params.get( keys[ i ],j ) ;
                    if( v == null || ( v = v.trim() ).length() <= 0 ) {
                        buf.append( keys[ i ] ).append( "=" ) ;
                    }
                    else {
                        buf.append( keys[ i ] ).append( "=" ).
                            append( convert( v,charset ) ) ;
                    }
                    cnt ++ ;
                }
            }
            return buf.toString() ;
        }
        return null ;
    }
    
    /**
     * 絵文字エンコード.
     */
    public static final String convert(String value,String charset)
        throws Exception {
        if (value == null || (value = value.trim()).length() <= 0) {
            return null;
        }
        StringBuffer buf = new StringBuffer();
        int len = value.length();
        for (int i = 0; i < len; i++) {
            char c = value.charAt(i);
            byte[] b = new String(new char[] { c }).getBytes(charset);
            int lenJ = b.length;
            for (int j = 0; j < lenJ; j++) {
                String hex = Integer.toHexString(
                        ((int) b[j]) & 0x000000ff).toLowerCase();
                hex = "00".substring( hex.length() ) + hex ;
                buf.append("%");
                buf.append(hex);
            }
        }
        return buf.toString();
    }
}
