/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program 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.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.accesstracking;


import scone.proxy.HtmlTokenEditor;
import scone.util.ErrorLog;
import scone.util.tokenstream.HtmlTagToken;
import scone.util.tokenstream.HtmlTextToken;
import scone.util.tokenstream.SconePipe;
import scone.util.tokenstream.Token;
import scone.util.tokenstream.TokenInputStream;
import scone.util.tokenstream.TokenOutputStream;


/**
 * Adds events to the BODY-Tag to track the actions of a user. If the
 * page contains a frameset, the events will not be added, because
 * there will be no applet to communicate with.<P>
 *
 * <code>onLoad</code> is called after the page was loaded<BR>
 * <code>onUnload</code> is called when a page is left<P>
 *
 * @author Harald Weinreich
 * @author Volkert Buchmann
 * modified by Torsten Hass
 */
public class BodyEventAdder extends HtmlTokenEditor {

    public static final String COPYRIGHT = "(C) Harald Weinreich & Volkert Buchmann";
    private static final String onLoad = "_scone_loaded();";
    private static final String onUnload = "_scone_stop();";

    /**
     * tries to add load and unload-events to the body-tag<P>
     * if no body tag can be found before first:<OL>
     * <LI> heading
     * <LI> table
     * <LI> link (&lt;A&gt; or &lt;AREA&gt;-Tag
     * <LI> image
     * <LI> form
     * <LI> preformatted text
     * <LI> or before EOF
     * </OL>
     * a new body-tag is inserted.
     */
    public void handleRequest(SconePipe pipe) {
        try {
            TokenInputStream in = pipe.getTokenInputStream();
            TokenOutputStream out = pipe.getTokenOutputStream();

            HtmlTagToken tag = null;
            Token t = null;
            boolean written = false;
            boolean frameset = false;

            while ((t = in.read()) != null) {
                if (!written && (t instanceof HtmlTagToken)) {
                    tag = (HtmlTagToken) t;
                    if (tag.getTagType() == tag.T_FRAMESET) {
                        frameset = true;
                    }
                    // Add events to &lt;body&gt;-Tag
                    if ((tag.getTagType() == tag.T_BODY) && (!frameset)) {
                        // System.out.println("body tag found.");
                        String onLoad = this.onLoad;
                        String onUnload = this.onUnload;
                        String onBeforeUnload = this.onUnload;


                        // do the attributes exist? read and delete.
                        if (tag.hasParam("onload")) {
                            onLoad += tag.getParam("onload");
                            tag.removeParam("onload");
                        }
                        if (tag.hasParam("onunload")) {
                            onUnload += tag.getParam("onunload");
                            tag.removeParam("onunload");
                        }
                        if (tag.hasParam("onbeforeunload")) {
                            onUnload += tag.getParam("onbeforeunload");
                            tag.removeParam("onbeforeunload");
                        }

                        // insert new events
                        tag.setParam("onload", onLoad, "onLoad");
                        if (onUnload.length() > 0)  // Did we set an onUnload event?
                        {
                            tag.setParam("onunload", onUnload, "onUnload");
                        }
                        tag.setParam("onbeforeunload", onBeforeUnload, "onBeforeUnload");  // For the Internet Explorer to create events when a user closes a window...
                        written = true;
                    } else {
                        if ((tag.isInBody()) && (!frameset)) {
                            // System.out.println("Warning: No body tag! One of the other tags found: inserting body tag.");
                            HtmlTextToken nl = new HtmlTextToken("\n");  // Create New Line Tag
                            HtmlTagToken body = new HtmlTagToken("body");    // Create Body Tag

                            // insert new events
                            body.setParam("onload", onLoad, "onLoad");
                            body.setParam("onunload", onUnload, "onUnload");
                            out.write(nl);         // new line
                            out.write(body);       // write body-tag
                            out.write(nl);         // new line
                            written = true;
                        }
                    }
                }// if(!written && tag)
                out.write(t);
            }// while
        } catch (Exception exc) {
            ErrorLog.log(this, "handleRequest()", "", exc);
        }
    }

}
