/*
    Example of creation of a new Jaxe element: boolean element displayed with a checkbox
    compilation: javac -classpath .:Jaxe.jar JEBoolean.java
*/

import jaxe.JaxeDocument;
import jaxe.JaxeElement;

import java.awt.event.*;
import javax.swing.JCheckBox;
import javax.swing.text.Position;

import org.w3c.dom.*;

/**
 * Boolean element.
 * Possible values: "true" | "false" | "1" | "0"
 */
public class JEBoolean extends JaxeElement implements ItemListener {

    protected static final boolean defaultValue = false;
    
    protected JCheckBox checkbox;

    // display initialisation
    public void init(Position pos, Node node) {
        Element el = (Element)node;
        
        // getting the element value
        String title = el.getTagName();
        Node child = el.getFirstChild();
        String text = null;
        if (child != null)
            text = child.getNodeValue();
        
        // Swing element creation
        checkbox = new JCheckBox(title, stringToBoolean(text));
        checkbox.addItemListener(this);
        
        // insertion of the component in the text (insertComponent is a method of JaxeElement)
        insertComponent(pos, checkbox);
    }
    
    protected static boolean stringToBoolean(String s) {
        if (s != null)
            s = s.trim();
        if ("true".equals(s) || "1".equals(s))
            return(true);
        else if ("false".equals(s) || "0".equals(s))
            return(false);
        else
            return(defaultValue);
    }
    
    protected static String booleanToString(boolean b) {
        if (b)
            return("true");
        else
            return("false");
    }
    
    // creation of a new DOM element
    public Node nouvelElement(Element refElement) {
        Element newel = nouvelElementDOM(doc, refElement);
        Node textnode = doc.DOMdoc.createTextNode(booleanToString(defaultValue));
        newel.appendChild(textnode);
        return(newel);
    }
    
    // updating the attributes display according to the DOM: nothing to do for JEBoolean
    //public void majAffichage() { }
    
    public void itemStateChanged(ItemEvent e) {
        setValue(checkbox.isSelected());
    }
    
    public void setValue(boolean value) {
        Element el = (Element)noeud; // noeud is the DOM node for this JaxeElement
        Node child = el.getFirstChild();
        if (child != null)
            child.setNodeValue(booleanToString(value));
        else {
            Node textnode = doc.DOMdoc.createTextNode(booleanToString(value));
            el.appendChild(textnode);
        }
    }
}