/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 C.Marchand - christophe.marchand@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.widgets.generic;

import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
import fr.gouv.finances.cp.xemelios.widgets.AbstractWidget;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;

/**
 *
 * @author chm
 */
public class SaveAs extends AbstractWidget {
    private static Logger logger = Logger.getLogger(SaveAs.class);
    
    /** Creates a new instance of SaveAs */
    public SaveAs(WidgetModel wm, ElementModel em) {
        super(wm,em);
    }
    public void run(EtatResultTableModel etrm,int row) {
        try {
            DataHandler dh = etrm.getRowAt(row,0);
            Document doc = dh.getDocument();
            String encoding = dh.getDocumentEncoding();
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.setOutputProperty(OutputKeys.ENCODING,encoding);
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Enregistrer "+("male".equals(getWidgetModel().getParam("gender").getValue())?"le":"la")+" "+getElementModel().getTitre()+" sous...");
            // @todo: mettre les bons filtres
//            chooser.addChoosableFileFilter(new LocalFileFilter("XML","Fichiers XML"));
//            chooser.addChoosableFileFilter(new LocalFileFilter(getElementModel().getParent().getParent().getExtension(),getElementModel().getParent().getParent().getTitre()));
//            chooser.addChoosableFileFilter(new FileFilter() {
//                public boolean accept(File f) { return true; }
//                public String getDescription() { return "Tous les fichiers"; }
//            });
            chooser.setFileFilter(new FileFilter(){
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toUpperCase().endsWith(".XML");
                }
                @Override
                public String getDescription() { return "Fichier XML"; }
            });
            File saveTo = null;
            boolean bContinue = true;
            while(bContinue) {
                    if(JFileChooser.APPROVE_OPTION==chooser.showSaveDialog(MainWindow.instance)) {
                        File f = chooser.getSelectedFile();
                        String fileName = f.getAbsolutePath();
                        int len = fileName.length();
                        if(fileName.substring(len-4).indexOf('.')<0) {
                            fileName=fileName+".xml";
                            f = new File(fileName);
                        }
                        if(f.exists()) {
                            int ret = JOptionPane.showConfirmDialog(MainWindow.instance,f.getAbsolutePath()+"\nexiste. Voulez-vous l'écraser ?","Ecrasement de fichier",JOptionPane.YES_NO_CANCEL_OPTION);
                            switch (ret) {
                                case JOptionPane.NO_OPTION: break;
                                case JOptionPane.YES_OPTION: saveTo=f;
                                case JOptionPane.CANCEL_OPTION: bContinue=false;
                            }
                        } else {
                            saveTo = f;
                            bContinue=false;
                        }
                    } else {
                        bContinue = false;
                    }
            }
            if(saveTo!=null) {
                logger.debug("writting");
                FileOutputStream fos = new FileOutputStream(saveTo,false);
                StreamResult sr = new StreamResult(fos);
                t.transform(new DOMSource(doc),sr);
                fos.flush(); fos.close();
            }
        } catch(Exception ex) {
            logger.error("in run: ",ex);
        }
    }
    
    private static class LocalFileFilter extends FileFilter {
        private String ext, description;
        public LocalFileFilter(String ext, String desc) {
            super();
            this.ext=ext;
            this.description=desc;
        }
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toUpperCase().equals(ext);
        }

        public String getDescription() { return description; }
    }

}
