/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 C.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 Lesser General Public License as published by
 * the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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.xhtmlviewer;


import fr.gouv.finances.cp.xemelios.common.Constants;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.util.logging.Level;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import org.apache.log4j.Logger;

import org.w3c.dom.Document;

import org.xhtmlrenderer.css.style.derived.RectPropertySet;
import org.xhtmlrenderer.event.DocumentListener;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.render.Box;
import org.xhtmlrenderer.swing.ScalableXHTMLPanel;


import java.awt.Point;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;



/**
 *
 * @author chm
 */
public class XemeliosXhtmlPanel extends ScalableXHTMLPanel {
    private static final Logger logger = Logger.getLogger(XemeliosXhtmlPanel.class);
    private JInternalFrame iframe;
    private JFrame frame;


    public XemeliosXhtmlPanel(UserAgentCallback uac, JInternalFrame frame) {
        super(uac);
        this.iframe=frame;
        addDocumentListener();
        addMonospacedFont();
    }
    public XemeliosXhtmlPanel(UserAgentCallback uac, JFrame frame) {
        super(uac);
        this.frame=frame;
        addDocumentListener();
        addMonospacedFont();
    }
    
    private void addMonospacedFont() {
        try {
            if(
                    MainWindow.instance!=null && 
                    !MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}").equals("${"+Constants.SYS_PROP_RESOURCES_LOCATION+"}")) {
                Font font = Font.createFont(Font.TRUETYPE_FONT, new File(new File(MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}")), "couri.ttf"));
                getSharedContext().setFontMapping("monospace", font);
            }
        } catch (FontFormatException ex) {
            logger.error(ex);
        } catch (IOException ex) {
            logger.error(ex);
        } catch(NullPointerException npEx) {
            logger.error(npEx);
        }
    }
    private void addDocumentListener() {
        addDocumentListener(new DocumentListener() {
            public void documentLoaded() {
                String sUrl = getSharedContext().getUac().getBaseURL();
                try {
                    URL __url = new URL(sUrl);
                    String url      = __url.toExternalForm();
                    int    sharpPos = url.indexOf('#');

                    if (sharpPos >= 0) {
                        String anchorName = url.substring(sharpPos + 1);
                        Box    box        =
                            getSharedContext().getBoxById(anchorName);

                        if (box != null) {
                            Point pt;

                            if (box.getStyle().isInline()) {
                                pt = new Point(box.getAbsX(), box.getAbsY());
                            } else {
                                RectPropertySet margin =
                                    box.getMargin(getLayoutContext());

                                pt = new Point(
                                    box.getAbsX() + (int) margin.left(),
                                    box.getAbsY() + (int) margin.top());
                            }

                            Point transPoint = new Point((int) (pt.getX()/ getScale()), (int) (pt.getY()/ getScale()));

                            scrollTo(transPoint);
                            repaint();

                            return;
                        } else {
                            logger.error("anchor not found: " + anchorName);
                        }
                    }
                    displayTitle(getDocumentTitle());
                } catch(MalformedURLException muEx) {
                    // ignorable
                }
            }
            public void onLayoutException(Throwable throwable) {}
            public void onRenderException(Throwable throwable) {}
            public void documentStarted() {}
        });
    }

    public JInternalFrame getFrame() {
        return iframe;
    }
    protected void displayTitle(String title) {
        if(title!=null) {
            if(frame!=null) frame.setTitle(title);
            if(iframe!=null) iframe.setTitle(title);
        }
    }

    //~--- set methods --------------------------------------------------------

    public void setDocument(File file) throws Exception {
        setScalePolicy(SCALE_POLICY_FIT_WIDTH);
        super.setDocument(file);
    }

    public void setDocument(Document doc, String url) {
        setScalePolicy(SCALE_POLICY_FIT_WIDTH);
        super.setDocument(doc, url);
    }

    public void setDocument(InputStream stream, String url) throws Exception {
        setScalePolicy(SCALE_POLICY_FIT_WIDTH);
        super.setDocument(stream, url);
    }
}

