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

import java.util.Hashtable;

import scone.netobjects.LinkToken;
import scone.proxy.AddPreambleEditor;
import scone.proxy.GeneralResourceGenerator;
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;

/**
 * is a Scone-plugin, that parses ``multilink´´-tags to create DHTML-popup links with
 * multiple destinations. <P>
 * ATTENTION:<BR>
 * The MultilinkExpander-Plugin is needed (either on server- or on client-side) to create the
 * multilink-tags.
 *
 * @author Volkert Buchmann (Main coding)
 * @author Harald Weinreich (Debugging and main UI design)
 */
public class BuildPopupClientside extends scone.Plugin{
   public static final String COPYRIGHT="(C) Volkert Buchmann";

   //requirements
   public int getRequirements(){
      return PARSEDOCUMENT | RESOURCEGENERATOR | ADDPREAMBLE;
   }

    public void init(){
        try{
            GeneralResourceGenerator.addPath("http://_servlink.scone.de/res","resources/servlink");
            AddPreambleEditor.addPreambleString("<LINK rel=stylesheet type='text/css' href='http://_servlink.scone.de/res/style.css'>\n");
            AddPreambleEditor.addPreambleString("<SCRIPT Language='JavaScript1.2' SRC='http://_servlink.scone.de/res/script.js'></SCRIPT>\n");

            Builder b=new Builder();
            b.setup("Builder",HTDOCCONDITION,50);
            addMeg(b);

        }catch(Exception e){
            ErrorLog.log(this,"init()","Could not init BuildPopupClientside plugin!",e);
        }
    }

    class Builder extends HtmlTokenEditor{

        public Hashtable readLinkElement(String name, TokenInputStream in) throws Exception {
            Hashtable element=new Hashtable();
            Token t=null;
        HtmlTagToken tag=null;
        boolean inElement=false;
        boolean inTitle=false;
        String title="";
            while((t=in.read())!=null){

                if(t instanceof HtmlTagToken){
                    if(((HtmlTagToken)t).getTagString().equals("multilink") && ((HtmlTagToken)t).isEndTag())
                        return null;

                    if(!inElement && ((HtmlTagToken)t).getTagString().equals(name)){
                            element.put("tag",t);
                            inElement=true;
                            continue;
                    }
                    if(inElement){
                        if(((HtmlTagToken)t).getTagString().equals("title")){
                            inTitle=true;
                            continue;
                        }
                        if(((HtmlTagToken)t).getTagString().equals("title") && ((HtmlTagToken)t).isEndTag()){
                            inTitle=false;
                            continue;
                        }
                        if(((HtmlTagToken)t).getTagString().equals(name)  && ((HtmlTagToken)t).isEndTag()){
                            element.put("title",safeString(title));
                            return element;
                        }
                    }
                }
                if(inTitle)
                    title+=t.toString();
            }
            element.put("title",safeString(title));
            return element;
        }

        //makes the string safe for jscript strings!
        public String safeString(String in){
            return in.replace('\'','´').replace('\n',' ');
        }



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

            LinkToken lt=null;
            HtmlTagToken tag=null;
            Token t=null;
            boolean inLink=false;
            String linkText="";
            int linkCount=0;
            // System.out.println("BuildPopupClientside: handleRequest()");
            while((t=in.read())!=null){

                /*
                if(t instanceof HtmlTagToken){
                    System.out.println(((HtmlTagToken)t).getTagString());
                }
                */

                if((t instanceof HtmlTagToken) && ((HtmlTagToken)t).getTagString().equals("multilink")){
                    // System.out.println("BuildPopupClientside: multilink found!");
                    Hashtable element=readLinkElement("original",in);
                    if(element==null)
                        continue;

                    linkCount++;
                    int i=0;

                    out.write(new HtmlTextToken(((HtmlTagToken)t).getWhiteSpaces()));

                    tag=new HtmlTagToken("script");
                    tag.setParam("language","JScript");
                    tag.setParam("type","text/jscript");
                    out.write(tag);

                    tag=(HtmlTagToken)element.get("tag");
                    out.write(new HtmlTextToken("beginpopup('popup"+linkCount+"', '"+((String)element.get("title")).replace((char)13,(char)32)+"', '"+tag.getParam("xlink:href")+"');"));

                    while((element=readLinkElement("alternative",in))!=null){
                        i++;
                        tag=(HtmlTagToken)element.get("tag");
                        if(tag!=null)
                            out.write(new HtmlTextToken("choice('test"+linkCount+"_"+i+"','related', '"+element.get("title")+"', '"+tag.getParam("xlink:href")+"');"));
                        }

                        out.write(new HtmlTextToken("endpopup();"));
                        out.write(new HtmlTagToken("/script"));
                        continue;
                    }

                  out.write(t);
               }//while
          }catch(Exception exc){
             ErrorLog.log(this,"BuildPopupClientside: handleRequest()","",exc);
          }
       }
    }
}



