/*
 * 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.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;


/**
 * Inserts a piece of JavaScript code on top of HTML-Page, that stores the actual Time. This is 
 * needed to calculate load time and staytime.<P>
 *
 * The following Code is inserted: <BR>
 * &lt;script type="text/javascript"&gt;<br>
 * &lt;!--<br>
 * var _scone_start_time=(new Date).getTime();<br>
 * //--&gt;<br>
 * &lt;/script&gt;
 *
 * @author Harald Weinreich
 * @author Volkert Buchmann
 * @author Torsten Hass
 */
public class TimeStoreScriptAdder extends HtmlTokenEditor {

    public static final String COPYRIGHT = "(C) Harald Weinreich & Volkert Buchmann & Torsten Hass";

    /**
     * tries to add the JavaScript code at beginning of HTML-file:
     */

    public void handleRequest(SconePipe pipe) {
        try {
            TokenInputStream in = pipe.getTokenInputStream();
            TokenOutputStream out = pipe.getTokenOutputStream();

            boolean written = false;
            boolean frameset = false;
            Token t = null;
            HtmlTagToken tag = null;
            HtmlTextToken preamble = new HtmlTextToken("\n<script type='text/javascript'>\n<!--\nvar _scone_start_time=(new Date).getTime();\n//-->\n</script>\n");

            while ((t = in.read()) != null) {

                if (!written && (t instanceof HtmlTagToken) && !t.toString().startsWith("<!") ) {
                    tag = (HtmlTagToken) t;
                    out.write(preamble);   // write preamble
                    written = true;
                }
                out.write(t);
            }
        } catch (Exception exc) {
            exc.printStackTrace();

        }
    }

}
