/*
 * Copyright 
 *   2008 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert@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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.ui;

import fr.gouv.finances.dgfip.xemelios.common.Constants;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import java.io.File;
import java.util.Hashtable;

import fr.gouv.finances.cp.xemelios.controls.editors.EditorHtmlViewer;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 *
 * @author lm (servilement copie sur StandaloneController.java)
 */
public class ViewXemeliosDocument {
    private DocumentsModel config = null;
    
    public static final transient String USAGE = "ViewXemeliosDocument [<fileToDisplay> [docId]]\n"+
            "where\n"+
            "\t<fileToDisplay> is the file to display\n"+
            "\tdocId is the id of doc-type.\n";

    private void init() throws Exception {
        config = Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
    }
    public ViewXemeliosDocument() throws Exception {
        init();
        JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
        jfc.addChoosableFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".xml");
            }
            @Override
            public String getDescription() {
                return "Fichiers XML";
            }
        });
        jfc.addChoosableFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return true;
            }
            @Override
            public String getDescription() {
                return "Tous les fichiers";
            }
        });
        jfc.setMultiSelectionEnabled(false);
        if(jfc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {
            File f = jfc.getSelectedFile();
            AskDocumentType adt = new AskDocumentType(null, f.getName(), config);
            adt.setVisible(true);
            DocumentModel dm = adt.getDocumentType();
            openFile(f.getAbsolutePath(),dm.getId());
        }
    } 
    public ViewXemeliosDocument(String inFileName) throws Exception {
        init();
        AskDocumentType adt = new AskDocumentType(null, inFileName, config);
        adt.setVisible(true);
        DocumentModel dm = adt.getDocumentType();
        openFile(inFileName,dm.getId());
    }

    public ViewXemeliosDocument(String inFileName, String docId) throws Exception {
        init();
        openFile(inFileName,docId);
    }
    protected void openFile(String inFileName, String docId) throws Exception {
        DocumentModel docConfig = config.getDocumentById(docId);
        if(docConfig==null) {
            JOptionPane.showMessageDialog(null, docId+": configuration non trouvée.","Erreur",JOptionPane.ERROR_MESSAGE);
            return;
        }
        Hashtable<String, File> documents = new Hashtable<String, File>();
        StringBuffer uri = new StringBuffer();
        File fileToRead = new File(inFileName);
        File fichierEnrichi = null;
        
        if(docConfig.getGlobalImportXsltFile()!=null) {
            fichierEnrichi = new File(new File(System.getProperty("java.io.tmpdir")),"_"+fileToRead.getName()+"_");
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer tr = tFactory.newTransformer(new StreamSource(new File(docConfig.getBaseDirectory(),docConfig.getGlobalImportXsltFile())));
            StreamResult result = new StreamResult(fichierEnrichi);
            tr.transform(new StreamSource(fileToRead),result);
            result.getOutputStream().flush(); result.getOutputStream().close();
        } else {
            fichierEnrichi = fileToRead;
        }

        documents.put(docId, fichierEnrichi);
        uri.append("xemelios:/query?docId="+docId+"&etatId="+docConfig.getDefaultEtatGlobal());
        EditorHtmlViewer ehv = new EditorHtmlViewer(documents, config, uri.toString(),new LocalUser());
        ehv.setLocationRelativeTo(null);
        ehv.setVisible(true);
    }


    public static void main(String[] args) {
//        String docId = "PES_Aller";
//        String strFile = "/home/chm/DGCP/magnus/PESALR1-21110429400015-011013-20070911122021704.xml";
        try {
            if(args.length> 1 && !(args[0].equals("")) && !(args[1].equals("")) ) {
                    new ViewXemeliosDocument(args[0],args[1]);
            } else if(args.length>=1 && !(args[0].equals(""))) {
                new ViewXemeliosDocument(args[0]);
            } else {
                new ViewXemeliosDocument();
            }
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        } 
    }

    /**
     * @TODO : AUTHORISATIONS A GERER CORRECTEMENT
     */
    public static class LocalUser implements XemeliosUser {

        public String getId() {
            return "local";
        }

        public String getDisplayName() {
            return getId();
        }

        public boolean hasRole(String arg0) {
            return true;
        }

        public boolean hasDocument(String arg0) {
            return true;
        }

        public boolean hasCollectivite(String arg0, DocumentModel dm) {
            return true;
        }

    }
}
