/**
 * 
 */
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) {
		String propertyName = evt.getPropertyName();
		Component component = null;
		
		if (propertyName.equals("AccessibleName")){
			AccessibleContext context = (AccessibleContext) evt.getSource();
			component = (Component) context.getAccessibleParent();
		}
		
		if (propertyName.equals("name")){
			component = (Component) evt.getSource();
		}
		
		if (propertyName.equals("")){
			
		}
		
		if (component != null){
			if (!JFCComponent.isKnown(component)){
				System.err.println("Referenced component is not known");
				throw new AssertionError("Referenced component is not known.");
			}
			StringBuilder builder = new StringBuilder();
			builder.append("<componentNameChange hash=\"");
			builder.append(Integer.toHexString(component.hashCode()));
			builder.append("\" newName=\"" + evt.getNewValue());
			builder.append("\" source=\"" + propertyName);
			builder.append("\" />" + StringTools.ENDLINE);
			outputWriter.write(builder.toString());
		}
	}
	
}
