/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.gouv.finances.cp.xemelios.widgets.generic;

import fr.gouv.finances.dgfip.xemelios.common.Constants;
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.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;

/**
 *
 * @author chm
 */
public class ViewCode extends AbstractWidget {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ViewCode.class);
    
    public ViewCode(WidgetModel wm, ElementModel em) {
        super(wm,em);
    }

    @Override
    public void run(EtatResultTableModel etrm, int row) {
        try {
            DataHandler dh = etrm.getRowAt(row,0);
            Document doc = dh.getDocument();
            String encoding = dh.getDocumentEncoding();
            TransformerFactory tf = net.sf.saxon.TransformerFactoryImpl.newInstance();
            Transformer t = tf.newTransformer(new StreamSource(new File(new File(MainWindow.instance.getEnvProperties().replace("${"+Constants.SYS_PROP_RESOURCES_LOCATION+"}")),"XMLPrettyPrint.xsl")));
//            t.setOutputProperty(OutputKeys.ENCODING,encoding);
//            t.setOutputProperty(OutputKeys.INDENT, "yes");
//            t.setOutputProperty(OutputKeys.METHOD, "xml");
            File tmpDir = new File(System.getProperty("java.io.tmpdir"));
            tmpDir = new File(tmpDir,Constants.NOM_APP);
            tmpDir.mkdirs();
            File tmp = File.createTempFile("xemelios-data-",".xml",tmpDir);
            FileOutputStream fos = new FileOutputStream(tmp,false);
            StreamResult sr = new StreamResult(fos);
            t.setParameter("title", getElementModel().getParent().getParent().getTitre());
            t.transform(new DOMSource(doc),sr);
            fos.flush(); fos.close();
            MainWindow.instance.displayHtmlStream(tmp, getElementModel().getParent());
            Transformer t2 = tf.newTransformer();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            t2.transform(new DOMSource(doc), new StreamResult(baos));
            baos.flush(); baos.close();
            logger.debug(baos.toString());
        } catch(Exception ex) {
            // TODO
        }
    }

}
