/**
 * 
 */
package de.ugoe.cs.quest.jfcmonitor;

import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.accessibility.AccessibleContext;

import de.ugoe.cs.util.StringTools;

/**
 * <p>
 * Listener that listens on the name change of a component.	
 * </p>
 * @author Fabian Glaser
 * @version 1.0
 */
public class JFCNameChangeListener implements PropertyChangeListener {
	 /**
     * <p>
     * Writer for logging events.
     * </p>
     */
    final private JFCMonitorOutputWriter outputWriter;
    
    /**
     * <p>
     * Constructor. Creates a new JFCNameChangeListener with a given 
     * {@link JFCMonitorOutputWriter}	
     * </p>
     * @param outputWriter
     */
    public JFCNameChangeListener(JFCMonitorOutputWriter outputWriter){
    	this.outputWriter = outputWriter;
    }
	
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("AccessibleName")){
			AccessibleContext context = (AccessibleContext) evt.getSource();
			Component component = (Component) context.getAccessibleParent();
			StringBuilder builder = new StringBuilder();
			builder.append("<componentNameChange hash=\"");
			if (!JFCComponent.isKnown(component)){
					System.err.println("Referenced component is not known");
					throw new AssertionError("Referenced component is not known.");
			}
			builder.append(Integer.toHexString(component.hashCode()));
			builder.append("\" newName=\"" + evt.getNewValue());
			builder.append("\"/>" + StringTools.ENDLINE);
			outputWriter.write(builder.toString());
		}		
	}
	
}
