package cz.kamma.kfmanager;

import cz.kamma.kfmanager.ui.MainWindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * Main application class for KF File Manager
 */
public class MainApp {

    public static final String APP_VERSION = "0.0.4";
    
    public static void main(String[] args) {
        // Set application name for X11/Wayland WM_CLASS
        System.setProperty("awt.app.name", "cz-kamma-kfmanager-MainApp");
        
        // Set look and feel to system default
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Enable arrow key navigation in JOptionPane dialogs
        setupGlobalKeyNavigation();
        
        // Start GUI in Event Dispatch Thread
        SwingUtilities.invokeLater(() -> {
            MainWindow mainWindow = new MainWindow();
            mainWindow.setVisible(true);
        });
    }

    private static void setupGlobalKeyNavigation() {
        Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
            if (event instanceof KeyEvent) {
                KeyEvent ke = (KeyEvent) event;
                if (ke.getID() == KeyEvent.KEY_PRESSED) {
                    int code = ke.getKeyCode();
                    if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT) {
                        Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                        if (focusOwner instanceof JButton) {
                            if (isInsideJOptionPane(focusOwner)) {
                                if (code == KeyEvent.VK_LEFT) {
                                    focusOwner.transferFocusBackward();
                                } else {
                                    focusOwner.transferFocus();
                                }
                                ke.consume();
                            }
                        }
                    }
                }
            }
        }, AWTEvent.KEY_EVENT_MASK);
    }

    private static boolean isInsideJOptionPane(Component c) {
        Component parent = c;
        while (parent != null) {
            if (parent instanceof JOptionPane) {
                return true;
            }
            parent = parent.getParent();
        }
        return false;
    }
}
