package uk.ac.starlink.topcat;

import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.util.function.Supplier;
import javax.swing.Action;

/**
 * Reports the STILTS command generated by the current state of a
 * supplied StiltsReporter component.
 *
 * @author   Mark Taylor
 * @since    19 Sep 2024
 */
public class StiltsAction extends BasicAction {

    private final StiltsReporter reporter_;
    private final Supplier<Window> parentSupplier_;
    private final Dimension size_;
    private StiltsDialog dialog_;

    /**
     * Constructs a StiltsAction with an explicitly sized dialogue.
     *
     * @param   reporter   component that can generate stilts command lines
     * @param   parentSupplier  provides a parent window for this action
     * @param   size   preferred size of the monitor panel that displays
     *                 the STILTS command; if null some default will be used
     */
    public StiltsAction( StiltsReporter reporter,
                         Supplier<Window> parentSupplier,
                         Dimension size ) {
        super( "STILTS", ResourceIcon.STILTS,
               "Show STILTS command corresponding to current window" );
        reporter_ = reporter;
        parentSupplier_ = parentSupplier;
        size_ = size == null ? new Dimension( 400, 200 )
                             : new Dimension( size );
    }

    /**
     * Constructs a StiltsAction with a default sized dialogue.
     *
     * @param   reporter   component that can generate stilts command lines
     * @param   parentSupplier  provides a parent window for this action
     */
    public StiltsAction( StiltsReporter reporter,
                         Supplier<Window> parentSupplier ) {
        this( reporter, parentSupplier, null );
    }

    public void actionPerformed( ActionEvent evt ) {
        if ( dialog_ == null ) {
            Window parent = parentSupplier_.get();
            dialog_ = new StiltsDialog( parent, reporter_, size_ );

            /* Place the dialogue next to the parent window. */
            if ( parent != null ) {
                dialog_.setLocation( parent.getX() + parent.getWidth(),
                                     parent.getY() );
            }
        }
        dialog_.setVisible( true );
    }
}
