/*
 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import javax.swing.KeyStroke;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/*
 * @test
 * @summary Verify that application menu bar may be specified
 * and used when no other frames are active.
 * @requires (os.family=="mac")
 * @run main AppMenuBarTest
 */

public class AppMenuBarTest {

    private static volatile boolean passed = false;
    private static void runTest() {
        if (!Desktop.isDesktopSupported() || 
            !Desktop.getDesktop().isSupported(Action.APP_MENU_BAR)) {
            System.out.println("Either Desktop or Action.APP_MENU_BAR is not supported. Pass.");
            passed = true;
            return;
        }
        JMenuBar bar = new JMenuBar();
        JMenu menu = new JMenu("File");
        JMenuItem menuItem = new JMenuItem("Menu Item");
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.META_MASK));
        menuItem.addActionListener(e ->  {System.err.println("action from menu item"); passed = true;});
        menu.add(menuItem);
        bar.add(menu);
        Desktop.getDesktop().setDefaultMenuBar(bar);
    }
    public static void main(String args[]) throws Exception {
        boolean isMac = System.getProperty("os.name").toLowerCase().contains("os x");
        if (!isMac) {
            System.out.println("It is not implemented not on OS X, in JDK9");
            System.exit(0);
        }
        SwingUtilities.invokeAndWait(AppMenuBarTest::runTest);
        Robot robot = new Robot();
        robot.setAutoDelay(50);
        robot.waitForIdle();
        robot.delay(300);

        if (passed) {
            System.out.println("Test passed.");
            return;
        }
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_M);
        robot.keyRelease(KeyEvent.VK_M);
        robot.keyRelease(KeyEvent.VK_META);

        robot.waitForIdle();
        robot.delay(300);
        if (passed) {
            System.out.println("Test passed.");
            System.exit(0);
        } else {
            //throw new RuntimeException("Test FAILED.");
            System.out.println("Test FAILED.");
            System.exit(1);
        }

    }
}
