package Action;

import IHM.WorkingImage;
import Window.Interface;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;

public class ActionOpenImage extends AbstractAction {

    public ActionOpenImage(String text, String desc, Integer mnemonic) {
        super(text);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser jc = new JFileChooser();
        if (jc.showOpenDialog(Interface.getInstance()) == JFileChooser.APPROVE_OPTION) {
            File file = jc.getSelectedFile();
            String path = file.getPath();
            if (!path.endsWith(".png") && !path.endsWith(".jpg") && !path.endsWith(".gif") && !path.endsWith(".bmp") && !path.endsWith("jpeg"))
                return;
            if (WorkingImage.getInstance().getImage() != null)
                Interface.getInstance().remove(WorkingImage.getInstance());
            String name = path;
            if (name.contains("/"))
                name = name.substring(name.lastIndexOf('/') + 1, name.length());
            if (name.contains("."))
                name = name.substring(0, name.lastIndexOf("."));
            if (name.contains("\\"))
                name = name.substring(name.lastIndexOf('\\') + 1, name.length());
            ImageIcon imageIcon = new ImageIcon(path);
            WorkingImage.getInstance().addImage(imageIcon, name);
            WorkingImage.getInstance().changeImage(WorkingImage.getInstance().getImages().indexOf(imageIcon));
            Interface.getInstance().setMenuBar();
            Interface.getInstance().showWindow();
        }
    }
}