/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 jp.tessier - jean-philippe.tessier@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.plugin.generatorEdmn;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import fr.gouv.finances.cp.utils.ui.InfiniteGlassPane;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;

/**
 *
 * @author jp.tessier
 */
public class DlgEdmnSaveAs extends javax.swing.JDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6249811846879359909L;
	private File directoryEdmnFiles = null;
	/** Taille du buffer pour les lectures/écritures */
	private static final int BUFFER_SIZE = 8 * 1024;
	    
    /** Creates new form NewJDialog */
    public DlgEdmnSaveAs(java.awt.Frame parent, boolean modal,File dirEdmnFiles) {
    	 super(parent, modal);
         this.directoryEdmnFiles=dirEdmnFiles;
         InfiniteGlassPane glassPane = new InfiniteGlassPane();
         this.setGlassPane(glassPane);
         initComponents();
         setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

    	button_saveAs = new javax.swing.JButton();
        text_saveAs = new javax.swing.JTextField();
        button_cancel = new javax.swing.JButton();
        button_valid = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sauvegarde du fichier EDMN");
        setAlwaysOnTop(true);
        setName("DlgEdmnSaveAs"); // NOI18N
        setResizable(false);

        button_saveAs.setText("Sauvergarder sous ...");
        button_saveAs.setName("button_saveAs"); // NOI18N
        button_saveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_saveAsActionPerformed(evt);
            }
        });

        text_saveAs.setEnabled(false);
        text_saveAs.setFocusable(false);
        text_saveAs.setName("text_saveAs"); // NOI18N
        text_saveAs.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                text_saveAsCaretUpdate(evt);
            }
        });

        button_cancel.setText("Annuler");
        button_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_cancelActionPerformed(evt);
            }
        });

        button_valid.setText("Sauvegarder");
        button_valid.setEnabled(false);
        button_valid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_validActionPerformed(evt);
            }
        });

        jLabel1.setText("Destination :");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 815, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel1)
                        .add(18, 18, 18)
                        .add(text_saveAs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 559, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(button_saveAs))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(button_valid)
                        .add(18, 18, 18)
                        .add(button_cancel)))
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 815, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 163, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(56, 56, 56)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(text_saveAs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(button_saveAs)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 29, Short.MAX_VALUE)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(button_cancel)
                    .add(button_valid))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void button_saveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_saveAsActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setApproveButtonText("Sélectionner");
        fc.setDialogTitle("Sélection du répertoire de sauvegarde");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File f) {
                if(f.isDirectory()){
                    return true;
                }
                return false;
            }
            public String getDescription() {
                return "Répertoires";
            }
        });
        int reponse = fc.showOpenDialog(this);
        if(reponse==JFileChooser.APPROVE_OPTION) {
            text_saveAs.setText(fc.getSelectedFile().getAbsolutePath());
        }
}//GEN-LAST:event_button_saveAsActionPerformed

    private void button_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_cancelActionPerformed
       this.dispose();
}//GEN-LAST:event_button_cancelActionPerformed

    private void text_saveAsCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_text_saveAsCaretUpdate
        if(text_saveAs.getText().length()>0){
            button_valid.setEnabled(true);
        }else{
            button_valid.setEnabled(false);
        }
}//GEN-LAST:event_text_saveAsCaretUpdate

    private void button_validActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_validActionPerformed
    	getGlassPane().setVisible(true);
    	try {
            //Création d'un flux d'écriture vers un fichier
            FileOutputStream fos = new FileOutputStream(new File(text_saveAs.getText(),"EDMN.xml.zip"));
            try {
                //Ajout du checksum : Adler32 (plus rapide) ou CRC32
                CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
                try {
                    //Création d'un buffer de sortie afin d'améliorer les performances
                    BufferedOutputStream bos = new BufferedOutputStream(checksum, BUFFER_SIZE);
                    try {
                        //Création d'un flux d'écriture Zip vers le fichier à  travers le buffer
                        ZipOutputStream zos = new ZipOutputStream(bos);
                        try {
                            //Compression maximale
                            try {
                                zos.setMethod(ZipOutputStream.DEFLATED);
                                zos.setLevel(Deflater.BEST_COMPRESSION);
                            }
                            catch (Exception ignor) {}
                            zipDir(directoryEdmnFiles.getAbsolutePath(), null, zos);
                        }
                        finally {
                            zos.close();
                        }
                    }
                    finally {
                        bos.close();
                    }
                }
                finally {
                    checksum.close();
                }
            }
            finally {
                fos.close();
            }
        }catch (IOException ioe){
            ioe.printStackTrace();
        }finally{
        	for(File f:directoryEdmnFiles.listFiles()){
        		if(!f.delete())System.out.println(f.getAbsolutePath()+" n'a pas été supprimé !");;
        	}
        	directoryEdmnFiles.delete();
        	getGlassPane().setVisible(false);
            setVisible(false);
            JOptionPane.showMessageDialog(MainWindow.instance,"Fichier sauvegardé.","Information",JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_button_validActionPerformed

    private static void zipDir(String basedir, String currentdir, ZipOutputStream zos) throws FileNotFoundException, IOException {
		//create a new File object based on the directory we have to zip
		File zipDir = (currentdir != null) ? new File(basedir, currentdir) : new File(basedir);
		//get a listing of the directory content
		String[] dirList = zipDir.list();
		byte[] readBuffer = new byte[BUFFER_SIZE];
		int bytesIn = 0;
		//On met pas File.separator, mais "/" parce que c'est le caractère utilisé
		//dans les ZIP.
		String currentdir2 = (currentdir != null) ? (currentdir + "/") : "";

		File f;
		FileInputStream fis;
		BufferedInputStream bis;
		ZipEntry anEntry;
		//Create an empty entry with just dir name, like WinZip, so unzipToDir will
		//behave correctly.
		if (currentdir2.length() > 0) {
			anEntry = new ZipEntry(currentdir2);
			zos.putNextEntry(anEntry);
			zos.closeEntry();
		}
		//loop through dirList, and zip the files
		for (int i = 0; i < dirList.length; i++) {
			f = new File(zipDir, dirList[i]);
			if (!f.exists())
				continue;
			if (f.isDirectory()) {
				//if the File object is a directory, call this
				//function again to add its content recursively
				zipDir(basedir, currentdir2 + dirList[i], zos);
				continue;
			}
			//if we reached here, the File object f was not a directory
			//create a FileInputStream on top of f
			fis = new FileInputStream(f);
			try {
				bis = new BufferedInputStream(fis, BUFFER_SIZE);
				try {
					//create a new zip entry
					anEntry = new ZipEntry(currentdir2 + dirList[i]);
					anEntry.setTime(f.lastModified());

					//place the zip entry in the ZipOutputStream object
					zos.putNextEntry(anEntry);
					//now write the content of the file to the ZipOutputStream
					while ((bytesIn = bis.read(readBuffer, 0, BUFFER_SIZE)) != -1) {
						zos.write(readBuffer, 0, bytesIn);
					}
					zos.closeEntry();
				}
				finally {
					bis.close();
				}
			}finally {
				//close the Stream
				fis.close();
			}
		}
	}

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DlgEdmnSaveAs dialog = new DlgEdmnSaveAs(new javax.swing.JFrame(),true,new File("C:\\\\Test\\\\EDMN\\\\CG"));
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton button_cancel;
    private javax.swing.JButton button_saveAs;
    private javax.swing.JButton button_valid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField text_saveAs;
    // End of variables declaration//GEN-END:variables

}
