/*
 * @(#)TextTool.java 5.1
 *
 */

package CH.ifa.draw.figures;

import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.net.URI;
import java.util.Objects;

import CH.ifa.draw.standard.CreationTool;
import CH.ifa.draw.util.FloatingTextField;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.TextHolder;
import de.renew.draw.ui.ontology.DrawingEditor;

/**
 * Tool to create new or edit existing target locations for figures.
 * The editing behavior is implemented by overlaying the
 * Figure providing the text with a FloatingTextField.
 * <p>
 * {@link FloatingTextField}
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
public class TargetTool extends CreationTool {

    /**
     * Logger for the class.
     */
    public static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(TargetTool.class);

    private static final String TARGET_LOCATION = "targetLocation";

    /**
     * FloatingTextField used to overlay the Figure providing the text in order to edit the target location.
     */
    protected FloatingTextField _textField;

    private Figure _typingTarget;

    /**
     * Constructor of the class TargetTool. Creates a new TargetTool with the given view.
     *
     * @param editor given view
     */
    public TargetTool(DrawingEditor editor) {
        super(editor, new TextFigure(false));
    }

    /**
     * A new text figure is created with the current target location.
     */
    @Override
    public void mouseDown(MouseEvent e, int x, int y) {
        TextFigure textFigure;

        if (_typingTarget != null) {
            endEdit();
            editor().toolDone();
        } else {
            _typingTarget = drawing().findFigureInside(x, y);
            if (_typingTarget != null) {
                String targetLocation = (String) _typingTarget.getAttribute(TARGET_LOCATION);
                super.mouseDown(e, x, y);
                textFigure = (TextFigure) createdFigure();
                textFigure.setText(Objects.requireNonNullElse(targetLocation, ""));
                //                textFigure.displayBox(new Rectangle(x,y,100,15));
                beginEdit(textFigure);
            }
        }
    }

    @Override
    public void mouseDrag(MouseEvent e, int x, int y) {}

    @Override
    public void mouseUp(MouseEvent e, int x, int y) {}

    /**
     * Terminates the editing of target location.
     */
    @Override
    public void deactivate() {
        super.deactivate();
        endEdit();
    }

    /**
     * Sets the text cursor.
     */
    @Override
    public void activate() {
        super.activate();
    }

    /**
     * Checks whether an editing session is currently active and returns a boolean accordingly.
     *
     * @return true if a figure is currently being edited, otherwise return false
     * @deprecated This method is currently not used and will be removed in a later version.
     */
    @Deprecated(since = "5.0", forRemoval = true)
    protected boolean isTypingActive() {
        return _typingTarget != null;
    }

    /**
     * Creates a <code>FloatingTextField</code> in order to enter a text for
     * the target location of a figure.
     *
     * @param figure - a figure, which holds the target location text.
     */
    public void beginEdit(TextFigure figure) {
        if (_textField == null) {
            _textField = new FloatingTextField();
            // listen for a text editing finish event (Ctrl-ENTER).
            _textField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent keyEvent) {
                    if (keyEvent.isControlDown() && keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                        deactivate();
                        editor().toolDone();
                    }
                }
            });
        }
        _textField.setText(figure.getText());
        _textField.createOverlay((Container) view(), fieldBounds(figure), figure.getFont());
        view().remove(figure);
    }

    /**
     * Sets the caret position to the given line and column.
     *
     * @param line line index
     * @param col column index
     * @deprecated This method is currently not used and will be removed in a later version.
     */
    @Deprecated(since = "5.0", forRemoval = true)
    public void setCaretPosition(int line, int col) {
        _textField.setCaretPosition(line, col);
    }

    /**
     * Ends the editing session for the target location.
     * <p>
     * If the new text is not empty, it is stored in TARGET_LOCATION.
     * If the input is empty, the target location is removed.
     * Also creates an undo snapshot and notifies the view of the change.
     */
    public void endEdit() {
        if (_typingTarget != null) {
            String newText = _textField.getText();
            String oldText = (String) _typingTarget.getAttribute(TARGET_LOCATION);
            if (newText.isEmpty()) { //remove current target location
                _typingTarget.setAttribute(TARGET_LOCATION, null);
            } else {
                try {
                    if (!newText.startsWith("sim")) {
                        URI uri = new URI(newText); //check if it is a URI
                        if (uri.isAbsolute()) {
                            uri.toURL(); //check if it is an absolute URI
                        }
                    }
                    _typingTarget.setAttribute(TARGET_LOCATION, newText);
                } catch (Exception e3) {
                    LOGGER.error("Renaming link failed for : " + newText);
                    LOGGER.debug(e3);
                }
            }

            _typingTarget = null;
            _textField.endOverlay();
            view().checkDamage();
            if (oldText != null) {
                if (!oldText.equals(newText)) {
                    changesMade();
                    intermediateUndoSnapshot();
                } else {
                    noChangesMade();
                }
            } else if (!newText.isEmpty()) {
                changesMade();
                intermediateUndoSnapshot();
            } else {
                noChangesMade();
            }
        }
    }

    private Rectangle fieldBounds(TextHolder figure) {
        /*
         * width and height are actually overridden by FloatingTExtField.
         * So only x,y coordinates are needed.
         */
        return figure.textDisplayBox();
    }
}