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

package CH.ifa.draw.figures;

import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;
import java.io.File;
import java.util.Objects;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.IOHelper;
import CH.ifa.draw.io.ImageFileFilter;
import CH.ifa.draw.standard.CreationTool;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.ui.ontology.DrawingEditor;

/**
 * A creation tool for inserting image figures into a drawing.
 * <p>
 * With the method {@code showFileDialog()} the user can input a path to an image that will be loaded. The Image, if
 * successfully loaded, will be placed at the position of the mouse click event.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
public class ImageFigureCreationTool extends CreationTool implements ImageObserver {
    /** Logger used for the class */
    public static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(ImageFigureCreationTool.class);
    private Image _image;
    private String _imageName = null;
    private final JFrame _frame;

    /**
     * Constructs a new ImageFigureCreationTool.
     *
     * @param editor editor that is used for coordinating the drawing process
     * @param frame {@code JFrame} Component that the instance is linked to
     */
    public ImageFigureCreationTool(DrawingEditor editor, JFrame frame) {
        super(editor);
        this._frame = frame;
    }

    private String showFileDialog() {
        IOHelper iohelper = Objects.requireNonNull(DrawPlugin.getCurrent()).getIOHelper();
        JFileChooser fc = new JFileChooser(iohelper.getLastPath());
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setFileFilter(new ImageFileFilter());
        fc.setFileHidingEnabled(true);
        fc.setMultiSelectionEnabled(false);
        int returnVal = fc.showOpenDialog(null);

        // File chooser was not approved?
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return null;
        }
        File file = fc.getSelectedFile();
        iohelper.setLastPath(file);
        return file.getAbsolutePath();
    }

    /**
     * Loads and returns an {@code Image} from the specified filename.
     *
     * @param fileName Name or Path of the image file that will be loaded
     * @param frame Component that the tracker, that ensures save loading, will be attached to
     * @return the loaded {@code Image} or {@code null} if loading the image has failed
     */
    public static Image createImage(String fileName, Component frame) {
        Image image = Toolkit.getDefaultToolkit().getImage(fileName);
        if (image != null) {
            MediaTracker tracker = new MediaTracker(frame);
            tracker.addImage(image, 123);
            // block until the image is loaded
            try {
                tracker.waitForAll();
            } catch (Exception e) {
                image = null;
            }
        }
        return image;
    }

    @Override
    public void activate() {
        super.activate();
        _image = null;
        _imageName = showFileDialog();

        if (_imageName != null) {
            _image = createImage(_imageName, _frame);
            if (_image == null) {
                noChangesMade();
                fEditor.toolDone();
                fEditor.showStatus("Image " + _imageName + " could not be loaded!");
            }
        } else {
            noChangesMade();
            fEditor.setStickyTools(false);
            fEditor.toolDone();
            fEditor.showStatus("Image creation canceled.");
        }
    }

    /**
     * Creates a new ImageFigure.
     */
    @Override
    protected Figure createFigure() {
        if (_imageName != null && _image != null) {
            Point pnt = fEditor.view().lastClick();
            ImageFigure imageFigure = new ImageFigure(_image, _imageName, pnt);
            Rectangle displayBox = imageFigure.displayBox();
            imageFigure.moveBy(-(displayBox.width / 2), -(displayBox.height / 2));
            return imageFigure;
        } else {
            return null;
        }
    }

    @Override
    public void mouseUp(MouseEvent e, int x, int y) {
        Figure created = createdFigure();
        if (created != null && created.isEmpty()) {
            Point loc = created.displayBox().getLocation();
            int width = _image.getWidth(this);
            int height = _image.getHeight(this);
            if (width == -1 || height == -1) {
                LOGGER.error("Image not loaded properly!");
            } else {
                created.displayBox(loc, new Point(loc.x + width, loc.y + height));
            }
        }
        super.mouseUp(e, x, y);
    }

    @Override
    synchronized public boolean imageUpdate(
        Image img, int infoflags, int x, int y, int width, int height)
    {
        return false;
    }
}