/**
 * 
 */
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;

/**
 * @author Fabian Glaser
 *
 */
public class JFCNameChangeListener implements PropertyChangeListener {
	 /**
     * <p>
     * Writer for logging events.
     * </p>
     */
    final private JFCMonitorOutputWriter 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());
		}		
	}
	
}
