package jp.sourceforge.acerola3d.a3editor;

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import jp.sourceforge.acerola3d.a3panels.*;
import javax.swing.*;
import java.io.File;
import javax.imageio.ImageIO;

class A3eA3Panel extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
    A3eFileManager fileManager;
    JButton snapshotB;
    A3Panel a3panel;
    A3eA3Panel(A3eFileManager fm) {
        fileManager = fm;
        setLayout(new BorderLayout());
        snapshotB = new JButton("サムネール画像を保存する");
        snapshotB.addActionListener(this);
        add(snapshotB,BorderLayout.NORTH);
        a3panel = new A3Panel(null);
        add(a3panel,BorderLayout.CENTER);
        
    }
    void loadAction3D(File f) {
        try {
            a3panel.loadAction3D(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void actionPerformed(ActionEvent e) {
        String fileName = JOptionPane.showInputDialog(this,"Input filename","thumbnail.jpg");
        File file = new File(fileManager.rootDir,fileName);
        BufferedImage orgImage = a3panel.snapshot();
        BufferedImage image = changeSize(orgImage,64,64);
        try {
            ImageIO.write(image,"jpg",file);
            fileManager.refresh();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
    BufferedImage changeSize(BufferedImage image, int width, int height) {
        ImageFilter filter = new AreaAveragingScaleFilter(width, height);
        ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
        Image newImage = Toolkit.getDefaultToolkit().createImage(ip);

        BufferedImage bufferedImage= new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setRenderingHints(new  RenderingHints(RenderingHints.KEY_ANTIALIASING,  RenderingHints.VALUE_ANTIALIAS_ON));
        graphics2D.drawImage(newImage, null, null);
        graphics2D.dispose();

        return bufferedImage;
    }
    void clear() {
        a3panel.clear();
    }
}
