package Action;

import IHM.WorkingImage;
import Window.Interface;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ActionSaveImage extends AbstractAction {
    public ActionSaveImage(String text, String desc, Integer mnemonic) {
        super(text);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(Action.MNEMONIC_KEY, mnemonic);
        if (WorkingImage.getInstance().getImages().size() == 0)
            setEnabled(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (WorkingImage.getInstance().getImages().size() == 0)
            return;
        JFileChooser jc = new JFileChooser();
        if (jc.showSaveDialog(Interface.getInstance()) == JFileChooser.APPROVE_OPTION) {
            File file = jc.getSelectedFile();
            String path = file.getPath();
            BufferedImage bufferedImage = WorkingImage.getInstance().getImage();
            if (!path.endsWith(".png"))
                path = path + ".png";
            file = new File(path);
            try {
                ImageIO.write(bufferedImage, "png", file);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}