package jp.sourceforge.acerola3d.a3editor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class CreateA3GUI extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
    A3eFileManager fileManager;
    JButton createB;
    public CreateA3GUI(A3eFileManager fm) {
        fileManager = fm;
        createB = new JButton("Acerola3Dファイルを作成");
        createB.addActionListener(this);
        this.add(createB);
    }
    void init() {
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            File rootDir = fileManager.rootDir;
            File defaultFile = new File(rootDir,rootDir.getName()+".a3");
            JFileChooser chooser = new JFileChooser(rootDir);
            chooser.setSelectedFile(defaultFile);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Acerola3D Files","a3");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showSaveDialog(this);
            if(returnVal!=JFileChooser.APPROVE_OPTION)
                return;
            File f = chooser.getSelectedFile();
            A3eFile files[] = fileManager.listA3eFile();
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
            byte[] buf = new byte[1024];
            for (A3eFile ff:files) {
                if (ff.isIgnored())
                    continue;
                if (ff.isDirectory())
                    continue;
                FileInputStream fis = new FileInputStream(ff.toFile());
                ZipEntry ze = new ZipEntry(ff.getPath());
                zos.putNextEntry( ze );
                int len = 0;
                while ((len = fis.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                fis.close();
                zos.closeEntry();
            }
            zos.close();

            fileManager.refresh();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    void clear() {
        //TODO
    }
}
