/*
 *
 * Copyright
 *  2007 axYus - www.axyus.com
 *  2007 Christophe 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 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.controls.editors;

import fr.gouv.finances.dgfip.utils.Pair;
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 fr.gouv.finances.cp.xemelios.controls.ControlContentHandler;
import fr.gouv.finances.cp.xemelios.controls.ControlProgressListener;
import fr.gouv.finances.cp.xemelios.controls.MainControl;
import fr.gouv.finances.cp.xemelios.controls.models.DocumentControlModel;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import java.io.File;
import java.math.BigDecimal;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 *
 * @author chm
 */
public class StandaloneController implements ControlProgressListener {
    
    private static final int MODE_CTRL = 1;
    private static final int MODE_DISPLAY = 2;
    
    /** Creates a new instance of StandaloneController */
    public StandaloneController(int mode) throws Exception {
        XemeliosUser localUser = new LocalUser();
        DocumentsModel config = Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));

        DocumentModel pesConfig = config.getDocumentById("PES_Aller");
        DocumentModel rapportConfig = config.getDocumentById("DocumentRapport");
        Hashtable<String, File> documents = new Hashtable<String,File>();
        StringBuffer uri = new StringBuffer();

        File fichierEnrichi = new File("/home/chm/tmp/pesv2-enrichi.xml");
        File rapport = new File("/home/chm/tmp/rapport.xml");
//        File fileToRead = new File("/home/chm/devel/RECETTE_XEMELIOS/3.3.0.5/fichiers/CONTROLE_PESV2_OK.xml");
//        File fileToRead = new File("/mnt/perso/christophe.marchand/PES_DEP_ET_REC_AVEC_PJ.xml");
        File fileToRead = new File("/home/chm/DGCP/magnus/PESALR1-25250828800039-025090-20090716125218898S.xml");
        File rapportEnrichi = new File("/home/chm/tmp/rapport-enrichi.xml");
        
        if(mode==MODE_CTRL) {
            MainControl mc = new MainControl(pesConfig,config) {
                public ControlContentHandler getControlContentHandler(DocumentModel dm,DocumentControlModel docCtrlMod,Hashtable<String,Object> parameters,JFrame frame,String file) {
                    ControlContentHandler cch = new ControlContentHandler(dm,docCtrlMod,parameters,(MainWindow)null,file) {
                        public Pair getCollectivite(DocumentModel dm, String fileName) {
                            return new Pair("xxxxxxxxxxx","Collectivité d'analyse");
                        }
                        public Pair getBudget(DocumentModel dm, Pair collectivite, String fileName) {
                            return new Pair("00","Budget principal");
                        }
                    };
                    return cch;
                }
            };
            mc.setControlProgressListener(this);

            File tmpEnrichi = new File(System.getProperty("java.io.tmpdir"),"tmp-pesv2-enrichi.xml");

            mc.setParameters(getControlParameters());
            mc.setFileToControl(fileToRead);
            mc.setFichierEnrichiLocation(tmpEnrichi.getAbsolutePath());
            mc.setRapportLocation(rapport.getAbsolutePath());

            // use any utility to run control
            mc.run();

            if(mc.getControlStatus()!=MainControl.STATUS_NOT_CONTROLLED) {
                if(mc.getControlStatus()>MainControl.STATUS_NOT_SCHEMA_VALID) {
                // on applique la XSL d'import specifique aux controle standalone au flux enrichi
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    Transformer tr = tFactory.newTransformer(new StreamSource(new File(pesConfig.getBaseDirectory(),pesConfig.getGlobalImportXsltFile())));
                    StreamResult result = new StreamResult(fichierEnrichi);
                    tr.transform(new StreamSource(tmpEnrichi),result);
                    result.getOutputStream().flush(); result.getOutputStream().close();
                    // change this if not forked
                    tmpEnrichi.deleteOnExit();

                    documents.put("PES_Aller",fichierEnrichi);
                }
                if(rapportConfig.getGlobalImportXsltFile()!=null && rapportConfig.getGlobalImportXsltFile().length()>0) {
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    Transformer tr = tFactory.newTransformer(new StreamSource(new File(rapportConfig.getBaseDirectory(),rapportConfig.getGlobalImportXsltFile())));
                    StreamResult result = new StreamResult(rapportEnrichi);
                    tr.transform(new StreamSource(rapport),result);
                    result.getOutputStream().flush(); result.getOutputStream().close();
                } else {
                    rapportEnrichi=rapport;
                }
                documents.put("DocumentRapport",rapportEnrichi);
                uri.append("xemelios:/query?collectivite=").append(mc.getCollectivite()!=null?mc.getCollectivite().key:"").append("&budget=").append(mc.getBudget()!=null?mc.getBudget().key:"");
                uri.append("&docId=DocumentRapport&etatId=DonneesRapport&path=[n:Id/@n:V='").append(mc.getIdRapport()).append("']");
            }
            tmpEnrichi.deleteOnExit();
        } else {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer tr = tFactory.newTransformer(new StreamSource(new File(pesConfig.getBaseDirectory(),pesConfig.getGlobalImportXsltFile())));
            StreamResult result = new StreamResult(fichierEnrichi);
            tr.transform(new StreamSource(fileToRead),result);
            result.getOutputStream().flush(); result.getOutputStream().close();
// DEBUG PURPOSES
            Transformer tra = tFactory.newTransformer();
            tra.transform(new StreamSource(fichierEnrichi), new StreamResult(System.out));

            documents.put("PES_Aller",fichierEnrichi);
            uri.append("xemelios:/query?docId=PES_Aller&etatId=general_view");
        }
        EditorHtmlViewer ehv = new EditorHtmlViewer(documents,config,uri.toString(),localUser);
        ehv.setLocationRelativeTo(null);
        ehv.setVisible(true);
    }
    
    protected Hashtable<String,Object> getControlParameters() {
        // in control config file, param types are
        //  string  -> java.lang.String
        //  boolean -> java.lang.Boolean
        //  decimal -> java.math.BigDecimal
        //  integer -> java.lang.Integer
        //
        // multi-valued params are String arrays (java.lang.String[]) values
        
        
        // here, filled with default values from PES as an example
        Hashtable<String,Object> ret = new Hashtable<String,Object>();
        ret.put("nomencl","M14");   // values can be M14, M21, M22, M31, M52, M61, M71
        ret.put("typnomencl","Nature"); // values can be Nature, Fonction, Nature-ref-fonct
        ret.put("votop",Boolean.FALSE);
        ret.put("suivdgp",Boolean.TRUE);
        ret.put("dureedgp",new Integer(45));
        ret.put("coltva",Boolean.TRUE);
        ret.put("servTVA",new String[] {}); // list of services
        ret.put("compteTVA",new String[] {}); // list of comptes
        ret.put("tauxTVA",new String[] {"2.1","5.5","19.6"}); // String array of VAT rates
        ret.put("seuilMax",new BigDecimal(90000));
        ret.put("seuilEmission",new BigDecimal(10));
        ret.put("codProd",new String[] {"69","70","71","72","73","74","75","76","77","78","79","80",
            "81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97",
            "98","99","100","101","102","103","104","105","106","107","248","300","302","305",
            "306","307","308"}); // String array of product codes
        return ret;
    }

    public void notifyImportFinished(MainControl.Triplet triplet) {}
    public void notifyImportInterrupted(boolean hide) {}
    public void stopWaiting() {}
    public void notifyTechniqueValidationFailed() {}

    public static void main(String[] args) {
        try {
            new StandaloneController(MODE_CTRL);
        } catch(Throwable t) {
            t.printStackTrace();
        }
    }

    /**
     * @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;
        }
        
    }
}
