package de.renew.navigator.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.Action;
import javax.swing.JFileChooser;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;

import CH.ifa.draw.DrawPlugin;
import de.renew.draw.ui.api.ApplicationApi;
import de.renew.navigator.FilesystemController;
import de.renew.plugin.PluginProperties;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstruction;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class AddFilesActionTest {

    @Mock
    FilesystemController fileSystemCtrl;

    @Mock
    PluginProperties _pluginProperties;

    private AddFilesAction action;
    private ActionEvent event;

    @BeforeEach
    void setUp() {
        action = new AddFilesAction(fileSystemCtrl, _pluginProperties);
        event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null);
    }

    @Test
    void metadata() {
        assertEquals("Add Files", action.getActionName());
        assertEquals("Add Files", action.getValue(Action.SHORT_DESCRIPTION));
    }

    @Test
    void doesNothingWhenNoPlugin() {
        try (MockedStatic<DrawPlugin> dp = mockStatic(DrawPlugin.class)) {
            dp.when(DrawPlugin::getCurrent).thenReturn(null);
            action.actionPerformed(event);
            verifyNoInteractions(fileSystemCtrl);
        }
    }

    @Test
    void performsLoadWhenApproved() {
        File file = mock(File.class);

        DrawPlugin plugin = mock(DrawPlugin.class);

        try (MockedStatic<DrawPlugin> dp = mockStatic(DrawPlugin.class);
            MockedStatic<ApplicationApi> applicationApi = mockStatic(ApplicationApi.class);
            MockedConstruction<JFileChooser> chooserMock =
                mockConstruction(JFileChooser.class, (chooser, ctx) -> {
                    when(chooser.showOpenDialog(null)).thenReturn(JFileChooser.APPROVE_OPTION);
                    when(chooser.getSelectedFiles()).thenReturn(new File[] { file });
                })) {
            dp.when(DrawPlugin::getCurrent).thenReturn(plugin);
            applicationApi.when(ApplicationApi::getLastPath).thenReturn(new File("/dummy"));
            action.actionPerformed(event);
            verify(fileSystemCtrl).loadRootDirectories(anyList());
            applicationApi.verify(ApplicationApi::getLastPath);
        }
    }
}