/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.servlet.facilities;

import org.bodington.servlet.*;
import org.bodington.server.realm.Permission;
import org.bodington.server.resources.*;
import org.bodington.server.*;
import org.bodington.servlet.template.Template;

import org.apache.log4j.Logger;

import java.util.Enumeration;
import java.io.*;
import javax.servlet.*;

public class EasyBuilderFacility extends SuiteFacility
{
    private static Logger log = Logger.getLogger(EasyBuilderFacility.class);
    
    public void insert( Request req, PrintWriter out, String command, String insertname )
    throws ServletException, IOException
    {
        log.debug( " EasyBuilderFacility insert()" );
        
        if ( command.equalsIgnoreCase( "update_minimenu" ) )
        {
            printJavaScriptToDisplayMiniMenuFrame(out);
            return;
        }
        
        if ( command.equalsIgnoreCase( "createcontainer" ) )
        {
            if ( req.getParameter("defaulturl") != null && out != null) {
                Resource new_resource;
                String container_name;
                
                new_resource = createconfirm( req, out, insertname, false );
                if ( new_resource == null )
                {
                    out.println("Creation of containing resource failed");
                    return;
                }
                
                // createconfirm() might have altered new resource's name, so get/set it here:
                container_name = new_resource.getName();
                
                printJavaScriptToRedirect(out, container_name);
            }
            
            return;
        }
        
        if ( command.equalsIgnoreCase( "createincontainer" ) )
        {
            if ( out!=null )
            {
                Resource new_resource;
                
                new_resource = createconfirm( req, out, insertname, false );
                
                if ( new_resource == null )
                {
                    return;
                }
                
                printJavaScriptToDisplayMiniMenuFrame(out);
            }
            return;
        }
        
        if (  command.equalsIgnoreCase( "uploadwithlink" ) )
        {
            if ( out!=null )
            {
                String file_name, link, errorMessage;
                Resource new_resource;
                boolean completed;
                
                file_name = req.getParameterFileName("file");
                // TODO Seems to be a bug in Bod code to check that the file exists?
                // (possible to upload a non-existent file...
                if ( file_name == null || file_name.equals( "" ))
                {
                    out.println( "No file name supplied" );
                    return;
                }
                
                new_resource = createconfirm( req, out, insertname, false );
                if ( new_resource == null )
                {
                    out.println("Creation of the link to the uploaded file has failed.<br />");
                    out.println("File has not been uploaded.");
                    return;
                }
                
                completed = upload( req, out, new_resource, true );
                
                errorMessage = "please use the <a href=\"bs_template_manage.html\">'Manage'<a> interface to correct this.";
                
                if ( !completed )
                {
                    // TODO rollback resource creation if upload fails?
                    out.println( "File upload failed, " + errorMessage );
                    return;
                    //           file_name = "bs_template_manage.html";
                }
                
                // TODO get full URL:
                link = "./" + new_resource.getName() + "/" + file_name;
                
                if ( new_resource instanceof QuickLink)
                {
                    try {
                        QuickLink quickLink = (QuickLink) new_resource;
                        quickLink.setNewWindow(true);
                        QuickLinkFacility.setLink(quickLink, link, req);
                        quickLink.save();
                    }
                    catch (BuildingServerException ex) {
                        out.println("The URL for the link could not be set, " + errorMessage);
                    }
                }
                else
                    out.println("The URL for the link could not be set, " + errorMessage);
                
                printJavaScriptToDisplayMiniMenuFrame(out);
            }
            
            return;
        }
        
        if ( command.equalsIgnoreCase( "shorttitle" ) )
        {
            if ( out != null )
            {
                try
                {
                    String title = req.getResource().getTitle();
                    if ( title != null )
                    {
                        if ( title.length() > 20 )
                            title = title.substring(0, 20) + "...";
                        
                        out.println( title );
                    }
                }
                catch (BuildingServerException e)
                {
                    // do nothing
                }
            }
            
            return;
        }
        
        if ( command.equalsIgnoreCase( "contentlist" ) )
        {
            if ( out != null )
                contentlist( req, out );
            
            return;
        }
        
        super.insert( req, out, command, insertname );
    }


    /**
     * Switches/updates left hand frame to display mini-menu (resource menu of resources in new container).
     * @param out Writer to write JavaScript to browser
     */
    private void printJavaScriptToDisplayMiniMenuFrame(PrintWriter out)
    {
        out.println("<script type=\"text/javascript\">");
        out.println("top.buildmain.graphic.location.href=\"bs_template_minimenu.html\";");
        out.println("top.buildmain.document.body.cols = \"220, *\";");
        out.println("</script>");
    }
    
    /**
     * Redirects menu frame to display easybuilder creation menu at container location.
     * @param out Writer to write JavaScript to browser
     * @param containerName Name of (newly-created) resource whose contents are to be displayed in the mini-menu
     */
    private void printJavaScriptToRedirect(PrintWriter out, String containerName)
    {
        out.println("<script type=\"text/javascript\">");
        out.println("top.buildtop.location.href=\""+ containerName +"/bs_template_top.html\";");
        out.println("top.buildmain.menu.location.href=\""+ containerName +"/bs_template_easybuildermenu.html\";");
        out.println("</script>");
    }
    
    /**
     * Resets left hand frame to normal display.
     * (If user presses back button in browser, they could end up with
     *  left hand frame displaying the minimenu when it shouldn't be.)
     * @param out Writer to write JavaScript to browser
     */
    public void printJavaScriptToResetLeftFrame(PrintWriter out)
    {
        out.println("<script type=\"text/javascript\">");
        out.println("top.buildmain.graphic.location.href=\"bs_template_graphic.html\";");
        out.println("</script>");
    }
    
    /**
     * Cut down version of {@link Facility#navigation(Request, PrintWriter, String)} method in Facility.
     * @param breq Request from UI
     * @param out Writer to output text to UI
     * @throws IOException
     */
    
    public void contentlist( Request breq, PrintWriter out )
    throws IOException
    {
        String smliconurl, parentsmliconurl;
        boolean tree;
        int n;
        BuildingContext context;
        FacilityList fl;
        Facility facility;
        Template template;
        String colour_mapper_code="";
        Resource resource, current, next;
        String tree_attribute;
        
        context = BuildingContext.getContext();
        fl = FacilityList.getFacilities();
        
        tree_attribute = (String)breq.getInsertAttribute( "tree", null );
        tree =  tree_attribute == null ||
        tree_attribute.equalsIgnoreCase( "yes" ) ||
        tree_attribute.equalsIgnoreCase( "true" );
        
        try
        {
            resource = context.getResource();
            
            parentsmliconurl = "bs_template_iconsmall.gif";
            template = Template.get( this.facilityname, resource.getImplicitHttpUIStyle(), null, "iconsmall.gif" );
            if ( template != null )
                parentsmliconurl = breq.getContextPath() + "/processedgif/templates" + template.getUrl() + colour_mapper_code;
            
            Enumeration enumeration=resource.findChildren();
            n=0;
            current=null;
            while ( enumeration.hasMoreElements() )
            {
                current = (Resource)enumeration.nextElement();
                if ( current.checkPermission( Permission.SEE ) )
                    break;
                current=null;
            }
            
            while( current!=null )
            {
                next=null;
                while ( enumeration.hasMoreElements() )
                {
                    next = (Resource)enumeration.nextElement();
                    if ( next.checkPermission( Permission.SEE ) )
                        break;
                    next=null;
                }
                
                // find url of small icon for current resource
                smliconurl = current.getName() + "/bs_template_navigation_iconsmall.gif";
                facility = fl.get( new Integer( current.getHttpFacilityNo() ) );
                if ( facility!=null )
                {
                    template = Template.get( facility.facilityname, current.getImplicitHttpUIStyle(), null, "iconsmall.gif" );
                    if ( template != null )
                        smliconurl = breq.getContextPath() + "/processedgif/templates" + template.getUrl() + colour_mapper_code;
                }
                
                if ( n==0 )
                {
                    // if we have found a resource to list start off the table
                    out.print( "<TABLE border=0 cellpadding=0 cellspacing=0>" );
                    if ( tree )
                    {
                        // first display
                        // icon for containing resource
                        out.print( "<TR><TD VALIGN=TOP COLSPAN=2>" );
                        out.print( "<IMG alt=\"" + iconName(resource) + ".\" BORDER=0 SRC=\"" );
                        out.print( parentsmliconurl );
                        out.print( "\">" );
                        //out.print( "</TD><TD>" );
                        out.println( "</TD></TR>" );
                        out.println( "<TR><TD VALIGN=TOP BACKGROUND=" + breq.getContextPath() + "/icons/thread-line.gif>" );
                        out.print( "<IMG BORDER=0 SRC=\"" + breq.getContextPath() + "/icons/thread-filler.gif\">" );
                        out.println( "</TD><TD></TD></TR>" );
                    }
                }
                n++;
                
                out.println( "<TR>" );
                
                if ( tree )
                {
                    if ( next==null )
                        out.println( "<TD VALIGN=TOP>" );
                    else
                        out.println( "<TD VALIGN=TOP BACKGROUND=" + breq.getContextPath() + "/icons/thread-line.gif>" );
                    out.println("<IMG SRC=" + breq.getContextPath() + "/icons/resource-arrow.gif>");
                    out.println( "</TD>" );
                }
                
                out.print( "<TD VALIGN=TOP>" );
                // <altAndTitle> --->>>
                out.print( "<IMG alt=\"" + iconName(current) + "\" CLASS=bs-links-icon BORDER=0 SRC=\"" );
                // <<<--- <altAndTitle>	
                out.print( smliconurl );
                out.print( "\">" );
                out.println( "</TD>" );
                
                out.print( "<TD VALIGN=TOP>" );
                out.print( "<SPAN CLASS=bs-links-title>" );
                out.print( current.getTitle() );
                //out.println( "</NOBR>" );
                out.println( "</SPAN>" );
                out.println( "</TD>" );
                
                out.println( "</TR>" );
                
                current = next;
            }
            if ( n>0 )
                out.println( "</TABLE>" );
            return;
        }
        
        catch ( BuildingServerException bsex )
        {
            return;
        }
    }
}
