/* UtilLib - Copyright (c) 2005-2006 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.text;

import java.io.UnsupportedEncodingException;


/**
 *
 * @author Vincent Calame
 */
public class UTF8Bridge {

    private static final short UTF8 = 11;
    private static final short ISO_8859_1 = 12;
    private static final short OTHER = 13;
    short type = OTHER;
    String charsetName;

    public UTF8Bridge(String charsetName) {
        if (charsetName != null) {
            this.charsetName = charsetName;
            if (charsetName.equals("UTF-8")) {
                type = UTF8;
            } else if (charsetName.equals("ISO-8859-1")) {
                type = ISO_8859_1;
            }
        } else {
            type = ISO_8859_1;
            this.charsetName = "ISO-8859-1";
        }
    }

    /**
     *
     *@throws UTF8BridgeException
     */
    public String toUTF8(String s) {
        if (type == UTF8) {
            return s;
        }
        if (s == null) {
            return null;
        }
        try {
            return new String(s.getBytes(charsetName), "UTF-8");
        } catch (UnsupportedEncodingException uue) {
            throw new UTF8BridgeException(charsetName, uue);
        }
    }

    public String getCharsetName() {
        return charsetName;
    }

}
