
package uk.co.wingpath.modbusgui;


import javax.swing.*;
import java.awt.event.*;
import uk.co.wingpath.gui.*;
import uk.co.wingpath.util.*;

public class RadixSelector
    extends WComboBox<Integer>
{
    public RadixSelector (boolean allowChar)
    {
        super ("Radix",
            allowChar ?
                new Integer [] { 2, 8, 10, 16, Numeric.RADIX_CHAR } :
                new Integer [] { 2, 8, 10, 16 },
            allowChar ?
                new String [] { "2", "8", "10", "16", "char" } :
                new String [] { "2", "8", "10", "16" });
        setValue (10);
        setAlignment (SwingConstants.CENTER);
        setToolTipText (
            allowChar ?
                new String []
                {
                    "Binary",
                    "Octal",
                    "Decimal",
                    "Hexadecimal",
                    "Characters"
                } :
                new String []
                {
                    "Binary",
                    "Octal",
                    "Decimal",
                    "Hexadecimal",
                });
        setWidthChars (allowChar ? 6 : 5);
        setToolTipText ("Radix to use to display value");
        setMnemonic (KeyEvent.VK_X);
    }

    public static String convertRadix (int radix)
    {
        return
            radix == Numeric.RADIX_CHAR ? "char" :
            Integer.toString (radix);
    }

    public static int convertRadix (String radixStr)
        throws ValueException
    {
        try
        {
            if (radixStr.equals ("char"))
                return Numeric.RADIX_CHAR;
            int radix = Integer.parseInt (radixStr);
            if (radix == 2 || radix == 8 || radix == 10 || radix == 16)
                return radix;
        }
        catch (NumberFormatException e)
        {
        }
        throw new ValueException ("Unrecognized radix: " + radixStr);
    }

    public int getRadix ()
    {
        return getValue ();
    }

    public void setRadix (int radix)
    {
        setValue (radix);
    }

    public void setRadix (String radix)
        throws ValueException
    {
        setValue (convertRadix (radix));
    }
}

