/*
 * 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.cp.xemelios.common.Constants;
import fr.gouv.finances.cp.xemelios.common.config.ElementModel;
import fr.gouv.finances.cp.xemelios.common.config.WidgetModel;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.cp.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.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 javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;

/**
 *
 * @author chm
 */
public class ViewCode extends AbstractWidget {
    
    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 = TransformerFactory.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());
        } catch(Exception ex) {
            // TODO
        }
    }

}
