package org.fest.swing.core;

import java.lang.reflect.InvocationTargetException;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.fest.swing.fixture.JLabelFixture;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Woody Folsom
 */
public class FestBug139Test {

    @Test
    public void testMain() {
        final JLabel label1 = new JLabel("testLabel");
        label1.setName("testLabel");

        final JLabel label2 = new JLabel("testLabel");
        label2.setName("testLabel");

        Robot robot = BasicRobot.robotWithCurrentAwtHierarchy();
        final JDialog dialog1 = new JDialog();
        final JDialog dialog2 = new JDialog();
        try {
            SwingUtilities.invokeAndWait(
                    new Runnable() {

                        public void run() {
                            dialog1.setName("testDialog");
                            dialog1.setVisible(true);
                            dialog1.getContentPane().add(label1);
                            dialog1.pack();
                        }
                    });

            //make a fixture for the first label
            new JLabelFixture(robot, "testLabel");
            //find the first label compoent
            robot.finder().findByName("testLabel");

            //dispose of the first dialog - now the first label should not
            //be matched by the findByName() invocation below, as it is no longer shown
            dialog1.dispose();
            
            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    dialog2.setName("testDialog");
                    dialog2.setVisible(true);
                    dialog2.getContentPane().removeAll();
                    dialog2.getContentPane().add(label2);
                    dialog2.pack();
                }
            });

            //If no error occurs on the next line, then neither should the line
            //immediately after when Bug #139 is fixed.
            new JLabelFixture(robot, "testLabel");
            robot.finder().findByName("testLabel");
        } catch (InterruptedException ie) {
            fail("interrupted: " + ie.getMessage());
        } catch (InvocationTargetException ite) {
            fail("interrupted: " + ite.getMessage());
        }

    }
}
