package cz.kamma.kfmanager.ui;

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

/**
 * Dialog for entering a wildcard pattern to select matching files
 */
public class WildcardSelectDialog extends JDialog {
    
    private JTextField patternField;
    private boolean confirmed = false;
    
    public WildcardSelectDialog(Frame parent) {
        super(parent, "Vybrat podle masky", true);
        initComponents();
        pack();
        setLocationRelativeTo(parent);
    }
    
    private void initComponents() {
        setLayout(new BorderLayout(10, 10));
        
        // Main panel with padding
        JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // Label
        JLabel label = new JLabel("Zadejte masku (např. *.txt, test*.*, file?.dat):");
        mainPanel.add(label, BorderLayout.NORTH);
        
        // Text field for pattern
        patternField = new JTextField("*", 30);
        patternField.selectAll();
        mainPanel.add(patternField, BorderLayout.CENTER);
        
        add(mainPanel, BorderLayout.CENTER);
        
        // Button panel
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
        JButton okButton = new JButton("OK");
        okButton.addActionListener(e -> {
            confirmed = true;
            dispose();
        });
        
        JButton cancelButton = new JButton("Zrušit");
        cancelButton.addActionListener(e -> {
            confirmed = false;
            dispose();
        });
        
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        
        add(buttonPanel, BorderLayout.SOUTH);
        
        // Enter confirms
        patternField.addActionListener(e -> {
            confirmed = true;
            dispose();
        });
        
        // ESC cancels
        getRootPane().registerKeyboardAction(e -> {
            confirmed = false;
            dispose();
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        
        getRootPane().setDefaultButton(okButton);
    }
    
    public String getPattern() {
        return confirmed ? patternField.getText().trim() : null;
    }
    
    @Override
    public void setVisible(boolean visible) {
        if (visible) {
            SwingUtilities.invokeLater(() -> {
                patternField.requestFocusInWindow();
                patternField.selectAll();
            });
        }
        super.setVisible(visible);
    }
}
