package de.renew.navigator.gui;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Action;
import javax.swing.KeyStroke;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import de.renew.navigator.NavigatorAction;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

public class TreeKeyListenerTest {
    private TreeKeyListener treeKeyListener;
    private NavigatorGuiImpl gui;

    @BeforeEach
    void setUp() {
        gui = mock(NavigatorGuiImpl.class);
        treeKeyListener = new TreeKeyListener(gui);
    }

    @Test
    public void enterKeyAndOpenSelectedFileTest() {
        //given
        KeyEvent keyEvent = new KeyEvent(
            mock(Component.class), KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, // no modifiers
            KeyEvent.VK_ENTER, '\n');

        //when
        treeKeyListener.keyReleased(keyEvent);

        //then
        verify(gui).openSelected();
    }

    @Test
    public void keyCodeZeroThenNothingHappensTest() {
        //given
        KeyEvent keyEvent = mock(KeyEvent.class);
        when(keyEvent.getKeyCode()).thenReturn(0);

        //when
        treeKeyListener.keyReleased(keyEvent);

        //then
        verifyNoInteractions(gui);
    }

    @Test
    public void unknownKeyThenNothingHappensTest() {
        //given
        KeyEvent keyEvent = new KeyEvent(
            mock(Component.class), KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, // no modifiers
            KeyEvent.VK_X, // “X” key
            'x');
        when(gui.getActions()).thenReturn(List.of());

        //when
        treeKeyListener.keyReleased(keyEvent);

        //then
        verify(gui, never()).openSelected();
    }

    @Test
    public void checkActionAcceleratorsThenActionPerformedTest() {
        //given
        NavigatorAction action = mock(NavigatorAction.class);
        when(action.getValue(Action.ACCELERATOR_KEY))
            .thenReturn(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK));
        when(gui.getActions()).thenReturn(List.of(action));

        KeyEvent keyEvent = new KeyEvent(
            mock(Component.class), KeyEvent.KEY_RELEASED, System.currentTimeMillis(),
            KeyEvent.CTRL_DOWN_MASK, // ctrl pressed
            KeyEvent.VK_R, 'r');

        //when
        treeKeyListener.keyReleased(keyEvent);

        //then
        verify(action).actionPerformed(null);
    }
}