package com.jxml.quick.editors;

import java.beans.PropertyEditorSupport;

/**
 * A PropertyEditor for "char" data.  Characters that are not legal XML
 * characters are represented textually as Java-style Unicode escapes
 * (e.g., "\\u001c").
 * <p>by Pavel Curtis--Quick 1.1
 */
public class CharEditor extends PropertyEditorSupport 
{
    public String getJavaInitializationString() 
    {
	if (charValue() == '\'')
	    return "'\\''";
	else
	    return "'" + getAsText() + "'";
    }

    private char charValue() 
    {
	return ((Character) getValue()).charValue();
    }

    public String getAsText() 
    {
	char ch = charValue();
	// Test for illegal XML characters and replace them with Java-style
	// Unicode escapes
	if ((ch < 0x20 && "\t\n\r".indexOf(ch) < 0)
	    || (ch > 0xD7FF && ch < 0xE000)
	    || ch > 0xFFFD) {
	    String s = "000" + Integer.toHexString(ch);
	    return "\\u" + s.substring(s.length() - 4);
	} else
	    return getValue().toString();
    }

    public void setAsText(String value) 
        throws IllegalArgumentException 
    {
	int ch;

	if (value == null)
	    throw new IllegalArgumentException(value);
	else if (value.length() == 1)
	    setValue(new Character(value.charAt(0)));
	else if (value.startsWith("\\u") && value.length() == 6
		 && (ch = parseHex(value.substring(2))) >= 0)
	    setValue(new Character((char) ch));
	else
	    throw new IllegalArgumentException(value);
    }

    private int parseHex(String value) 
    {
	try {
	    return Integer.parseInt(value, 16);
	} catch (NumberFormatException e) {
	    return -1;
	}
    }
}
