//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.jfcmonitor;

import java.awt.AWTEvent;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.WindowEvent;

/**
 * <p>
 * An AWT event listener responsible to monitor the window creation and destruction.
 * </p>
 * 
 * @author Steffen Herbold 
 * @author Fabian Glaser
 * @version 1.0
 */
public class JFCWindowMonitor implements AWTEventListener {
	 /**
     * <p>
     * Writer for logging events.
     * </p>
     */
    final private JFCMonitorOutputWriter outputWriter;	
	
    /**
     * <p>
     * Constructor. Creates a new JFCWindowMonitor with a given {@link JFCMonitorOutputWriter}, where the
     * monitored information is logged.
     * </p>
     * 
     * @param outputWriter
     *            writer for the logged information
     */
    public JFCWindowMonitor(JFCMonitorOutputWriter outputWriter) {
        this.outputWriter = outputWriter;
    }
	

    /**
     * <p>
     * Adds all created windows (and their child components) to the GUI hierarchy maintained by
     * {@link JFCComponent} and removes them if a window is destroyed.
     * </p>
     * </p>
     * 
     * @see java.awt.event.AWTEventListener#eventDispatched(java.awt.AWTEvent)
     */
    @Override
    public void eventDispatched(AWTEvent event) {
        Window window;
        switch (event.getID())
        {
            case WindowEvent.WINDOW_OPENED:
                window = ((WindowEvent) event).getWindow();
                JFCComponent.add(window);
                JFCComponent jfcComponent = JFCComponent.find(window);
                if (jfcComponent != null) {
                    outputWriter.write(jfcComponent.getXML());
                    outputWriter.write(jfcComponent.printChildren());
                }
                break;
            default:
                break;
        }
    }

}