package de.renew.gui.tool;


import java.awt.event.MouseEvent;

import CH.ifa.draw.standard.SelectAreaTracker;
import CH.ifa.draw.standard.StandardDrawingView;
import de.renew.draw.ui.ontology.DrawingEditor;
import de.renew.draw.ui.ontology.DrawingView;

public class ZoomAreaTool extends SelectAreaTracker {
    private DrawingView fFreezedView = null;

    public ZoomAreaTool(DrawingEditor editor) {
        super(editor);
    }

    @Override
    public void mouseDown(MouseEvent e, int x, int y) {
        try {
            if (fFreezedView == null) {
                fFreezedView = view();
                fFreezedView.freezeView();
            }
            super.mouseDown(e, x, y);
        } catch (RuntimeException | Error ex) {
            if (fFreezedView != null) {
                fFreezedView.unfreezeView();
                fFreezedView = null;
            }
            throw ex;
        }
    }

    @Override
    public void mouseUp(MouseEvent e, int x, int y) {
        if (fFreezedView != null) {
            fFreezedView.unfreezeView();
            fFreezedView = null;
        }
        super.mouseUp(e, x, y);
        editor().toolDone();
    }

    @Override
    protected void selectGroup(boolean toggle) {
        DrawingView view = view();
        boolean rectangleEmpty = (fSelectGroup.width < 3) || (fSelectGroup.height < 3);
        if (view instanceof StandardDrawingView standardDrawingView && !rectangleEmpty) {
            standardDrawingView.zoomToFitView(fSelectGroup);
        }
    }

    @Override
    public void deactivate() {
        if (fFreezedView != null) {
            fFreezedView.unfreezeView();
            fFreezedView = null;
        }
        super.deactivate();
    }
}