package jlama;

import com.formdev.flatlaf.util.UIScale;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ProgressDialog extends JDialog {
    private static final int SMALL_GAP = UIScale.scale(5);
    private static final int MEDIUM_GAP = UIScale.scale(10);
    private static final int LARGE_GAP = UIScale.scale(15);

    private final JLabel label;
    private final JProgressBar progressBar;

    public ProgressDialog(Window owner, Cancellable cancellable) {
        super(owner, "Downloading Model", ModalityType.APPLICATION_MODAL);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        label = new JLabel("Initializing...");
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(e -> cancellable.cancel());

        JPanel centerPanel = new JPanel(new BorderLayout(MEDIUM_GAP, 0));
        centerPanel.add(progressBar, BorderLayout.CENTER);
        centerPanel.add(cancelButton, BorderLayout.EAST);

        JPanel contentPanel = new JPanel(new BorderLayout(0, SMALL_GAP));
        contentPanel.setBorder(new EmptyBorder(LARGE_GAP, LARGE_GAP, LARGE_GAP, LARGE_GAP));

        contentPanel.add(label, BorderLayout.NORTH);
        contentPanel.add(centerPanel, BorderLayout.CENTER);

        getContentPane().add(contentPanel);
        addNotify();
        updateSize();
        setLocationRelativeTo(owner);

        addWindowListener(new WindowAdapter() {
            boolean activated;
            @Override
            public void windowActivated(WindowEvent e) {
                if (!activated) {
                    updateSize();
                    activated = true;
                }
            }
        });
    }

    private void updateSize() {
        pack();
        setMinimumSize(new Dimension(UIScale.scale(400), getPreferredSize().height));
    }


    public void setProgress(String text, int percent) {
        setText(text);
        progressBar.setValue(percent);
    }

    public void setText(String text) {
        label.setText(text);
    }

    public interface Cancellable {
        void cancel();
    }
}
