/*
 * StandaloneController.java
 *
 * Created on 14 novembre 2007, 10:36
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


package fr.gouv.finances.cp.xemelios.controls.editors;

import fr.gouv.finances.cp.utils.Pair;
import fr.gouv.finances.cp.xemelios.common.Constants;
import fr.gouv.finances.cp.xemelios.common.DematTransform;
import fr.gouv.finances.cp.xemelios.common.config.DocumentModel;
import fr.gouv.finances.cp.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.cp.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 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 {
        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-21110429400015-011013-20070911122021704.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,frame,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());
        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_DISPLAY);
        } catch(Throwable t) {
            t.printStackTrace();
        }
    }
}
