package cz.fidentis.analyst.symmetry;

import cz.fidentis.analyst.canvas.Canvas;
import cz.fidentis.analyst.core.ControlPanelAction;
import cz.fidentis.analyst.core.OutputWindow;
import cz.fidentis.analyst.scene.DrawablePlane;
import java.awt.event.ActionEvent;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;

/**
 * Action listener for the manipulation with the symmetry plane.
 * 
 * @author Radek Oslejsek
 */
public class SymmetryAction extends ControlPanelAction {

    private final SymmetryPanel controlPanel;

    /**
     * Constructor.
     * 
     * @param canvas OpenGL canvas
     * @param topControlPanel Top component for placing control panels
     */
    public SymmetryAction(Canvas canvas, JTabbedPane topControlPanel) {
        super(canvas, topControlPanel);
        this.controlPanel = new SymmetryPanel(this);
    }
    
    @Override
    public void actionPerformed(ActionEvent ae) {
        String action = ae.getActionCommand();
        DrawablePlane plane;
        
        switch (action) {
            case SymmetryPanel.ACTION_COMMAND_SHOW_HIDE_PANEL:
                hideShowPanelActionPerformed(ae, this.controlPanel);   
                break;
            case SymmetryPanel.ACTION_COMMAND_SHOW_HIDE_PLANE:
                plane = getCanvas().getScene().getDrawableSymmetryPlane(0);
                if (plane == null) { // no plane compute so far
                    break;
                }
                if (((JToggleButton) ae.getSource()).isSelected()) {
                    plane.show();
                } else {
                    plane.hide();
                }
                break;
            case SymmetryPanel.ACTION_COMMAND_RECOMPUTE: 
                recomputeSymmetryPlane();
                break;  
            default:
                // to nothing
        }
        renderScene();
    }
    
    private void recomputeSymmetryPlane() {
        OutputWindow out = OutputWindow.measureTime();
        
        SymmetryEstimator se = new SymmetryEstimator(controlPanel.getSymmetryConfig());
        getPrimaryDrawableFace().getModel().compute(se);
        DrawablePlane plane = new DrawablePlane(se.getSymmetryPlaneMesh(), se.getSymmetryPlane());
        getCanvas().getScene().setDrawableSymmetryPlane(0, plane);
        
        out.printDuration("Computation of Hausdorff distance for models with " 
                + getPrimaryDrawableFace().getHumanFace().getMeshModel().getNumVertices()
                + " vertices"
        );
    }
    
}
