package hyperscout;


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 a preamble to a Html-Document.
 * 
 * <br> 
 * The preamble is written before the &lt;body&gt;-Tag, or before the document body begins.<p>
 *
 * @author Harald Weinreich
 */

public class PreamblePopupCodeAdder extends HtmlTokenEditor {

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

    /**
     * tries to add the preamble:
     * <OL>
     * <LI> after  &lt;/frameset&gt;-Tag
     * <LI> before &lt;body&gt;-Tag
     * <LI> before heading
     * <LI> before table
     * <LI> before link (&lt;A&gt; or &lt;AREA&gt;-Tag
     * <LI> before image
     * <LI> before form
     * <LI> before preformatted text
     * </OL>
     */
    public void handleRequest(SconePipe pipe) {
        try {
            TokenInputStream in = pipe.getTokenInputStream();
            TokenOutputStream out = pipe.getTokenOutputStream();

            String preambleString = "<LINK rel=stylesheet type='text/css' href='http://_hyperscout.scone.de/res/popup.css'>\n";

            preambleString += "<SCRIPT Language='JavaScript1.2' SRC='http://_hyperscout.scone.de/res/popup.js'></SCRIPT>\n";
   		
            Token t = null;
            HtmlTagToken tag = null;
            boolean written = false;

            while ((t = in.read()) != null) {      
                if (!written && (t instanceof HtmlTagToken)) {   
                    tag = (HtmlTagToken) t;
                    if (((tag.getTagType() == tag.T_FRAMESET)
                                    && (tag.isEndTag()))
                            || (tag.getTagType() == tag.T_BODY)
                            ||    // the body is about to start...
                                    tag.isInBody()) {
                        out.write(new HtmlTextToken("\n" + preambleString + "\n"));
                        written = true;
                    }
                }// is HtmlTagToken
                out.write(t);
            }// while
        } catch (Exception exc) {
            ErrorLog.log(this, "handleRequest()", "", exc);
        }          
    }
}

