package de.renew.draw.ui.impl.menus.internal;

import java.awt.Component;
import java.awt.Toolkit;
import javax.swing.AbstractButton;
import javax.swing.JMenuItem;

import org.junit.jupiter.api.Test;

import CH.ifa.draw.application.DrawApplication;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

class MenuHelperTest {

    private static final String DUMMY_NAME = "Dummy-Name";

    @Test
    void testCreateMenuItemWithoutShortcut() {
        // given
        Runnable action = mock(Runnable.class);

        // when
        JMenuItem menuItem = MenuHelper.createMenuItem(DUMMY_NAME, action);

        // then
        assertThat(menuItem).isNotNull().returns(0, AbstractButton::getMnemonic)
            .returns(null, JMenuItem::getAccelerator)
            .returns(DrawApplication.getMenuFont(), Component::getFont)
            .returns(1, mi -> mi.getActionListeners().length);

        // Verify the action is run on click but not run before that.
        verify(action, never()).run();
        menuItem.doClick();
        verify(action).run();
    }

    @Test
    void testCreateMenuItemWithZeroAsShortcut() {
        // given
        int shortcut = 0;
        Runnable action = mock(Runnable.class);

        // when
        JMenuItem menuItem = MenuHelper.createMenuItem(DUMMY_NAME, shortcut, action);

        // then
        assertThat(menuItem).isNotNull().returns(shortcut, AbstractButton::getMnemonic)
            .returns(null, JMenuItem::getAccelerator)
            .returns(DrawApplication.getMenuFont(), Component::getFont)
            .returns(1, mi -> mi.getActionListeners().length);

        // Verify the action is run on click but not run before that.
        verify(action, never()).run();
        menuItem.doClick();
        verify(action).run();
    }

    @Test
    void testCreateMenuItemWithFilledShortcut() {
        // given
        int shortcut = 123;
        Runnable action = mock(Runnable.class);

        int expectedModifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();

        // when
        JMenuItem menuItem = MenuHelper.createMenuItem(DUMMY_NAME, shortcut, action);

        // then
        assertThat(menuItem).isNotNull().returns(shortcut, AbstractButton::getMnemonic)
            .returns(shortcut, mi -> mi.getAccelerator().getKeyCode())
            .returns(
                expectedModifiers, mi -> mi.getAccelerator().getModifiers() & expectedModifiers)
            .returns(DrawApplication.getMenuFont(), Component::getFont)
            .returns(1, mi -> mi.getActionListeners().length);

        // Verify the action is run on click but not run before that.
        verify(action, never()).run();
        menuItem.doClick();
        verify(action).run();
    }
}