/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

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

package org.bodington.servlet;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.awt.Color;
import java.awt.color.*;

import java.util.Enumeration;
import java.util.StringTokenizer;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.bodington.servlet.gif.*;
import org.bodington.util.ColourPreferenceMapper;

/**
 *
 * @author  jrm
 */
public class ProcessedGifServlet extends javax.servlet.http.HttpServlet
{
    
    private static Logger log = Logger.getLogger(ProcessedGifServlet.class);
    
    /** Creates a new instance of ProcessedGifServlet */
    public ProcessedGifServlet()
    {
    }
    
    public void init() throws ServletException
    {
        super.init();
    }
    
    public void doGet( HttpServletRequest req, HttpServletResponse resp )
    throws ServletException, IOException
    {
        doPost( req, resp );
    }
    
    
    public void doPost( HttpServletRequest req, HttpServletResponse res )
    throws ServletException, IOException
    {
        String path_info = req.getPathInfo();
        String path_translated = req.getPathTranslated();
        String code;
        
        if ( !path_info.startsWith( "templates" ) && !path_info.startsWith( "/templates" ) )
        {
            res.sendError( 403, "No access to files in requested area." );
            return;
        }
        
        if ( path_info.indexOf( ".." ) >= 0 )
        {
            res.sendError( 403, "Use of '..' in URLs is not allowed in requested area." );
            return;
        }
        
        File file = new File( path_translated );

        if ( !path_translated.endsWith( ".gif" ) )
        {
            res.sendError( 403, "Access in this area is restricted to GIF files only." );
            return;
        }

        if ( !file.exists() || !file.isFile() )
        {
            res.sendError( 404, "GIF file not found." );
            return;
        }
        
        
        GifDescriptor gd = GifDescriptor.getGifDescriptor( file );
        
        code = req.getParameter( "code" );
        ColourPreferenceMapper mapper = null;
        if ( code != null && code.length()>0 )
            mapper = new ColourPreferenceMapper( code );

        // at this point the servlet will either forward to the plain file
        // or programatically output a modified GIF.
        
        if ( mapper == null || gd.getGifColourStatements() == null )
            forwardToOriginal( req, res );
        else
            sendProcessedGif( req, res, mapper, gd );
        }
        
    public void forwardToOriginal( HttpServletRequest req, HttpServletResponse res )
    throws ServletException, IOException
    {
        String path_info = req.getPathInfo();
        ServletContext context=getServletContext();
        RequestDispatcher dispatcher=context.getRequestDispatcher( path_info );
        
        if ( dispatcher==null )
        {
            res.sendError( 500, "Technical problem fetching file - couldn't find dispatcher." );
            return;
        }
        
        // will it set up all the appropriate headers including those for cache control?
        dispatcher.forward( req, res );
    }
    
    public void sendProcessedGif( HttpServletRequest req, HttpServletResponse resp, ColourPreferenceMapper mapper, GifDescriptor gd )
    throws ServletException, IOException
    {
        Response res = new Response( resp );

        res.setContentType( "image/gif" );
        
        if ( ServletUtils.isModified(req, resp, gd.getLastModified(), 0) )
        {
            res.setStatus( HttpServletResponse.SC_NOT_MODIFIED );
            return;
        }
        
        ServletOutputStream out = res.getOutputStream();
        // output first part of header unmodified
        int count = gd.getColourCount();
        byte[] data = gd.getData();
        GifColourStatement[] statements = gd.getGifColourStatements();

        out.write( data, 0, 13 );

        if ( statements == null || statements.length == 0 )
            out.write( data, 13, 3*count );
        else
            sendProcessedGifColourTable( req, out, mapper, gd );


        if ( gd.isDataCached() )
            out.write( data, 13 + (count*3), data.length - (13 + (count*3)) );
        else
        {
            int n;
            FileInputStream fin = new FileInputStream( gd.getFile() );
            byte[] buffer = new byte[16*1024];
            fin.read( buffer, 0, 13 + (count*3) );

            while ( (n = fin.read( buffer, 0,  16*1024 ))> 0 )
                out.write( buffer, 0, n );
        }

        out.close();
    }
    
    public void sendProcessedGifColourTable( HttpServletRequest req, OutputStream out, ColourPreferenceMapper colour_mapper, GifDescriptor gd )
        throws java.io.IOException
    {
        Color b = colour_mapper.getReferenceBackgroundColor();
        Color f = colour_mapper.getReferenceForegroundColor();
        Color preferred_foreground = colour_mapper.getPreferredForegroundColor( f );
        Color preferred_background = colour_mapper.getPreferredBackgroundColor();
        Color active, gif_colour;
        
	int i, j, first, last;
        int count = gd.getColourCount();
        byte[] data = gd.getData();
	byte[] colourbuf = new byte[count*3];
        GifColourStatement[] statements = gd.getGifColourStatements();
	System.arraycopy( data, 13, colourbuf, 0, count*3 );
	
	for ( i=0; i<statements.length; i++ )
	{
	    if ( statements[i].index < GifColourStatement.ALL )
		continue;
	    if ( statements[i].index >= count )
		continue;
	    
            if ( !statements[i].author_can_modify && !statements[i].user_can_modify )
                continue;
            
	    if ( statements[i].index == GifColourStatement.ALL )
	    {
		first = 0;
		last = count-1;
	    }
	    else
	    {
		first = statements[i].index;
		last = statements[i].index;
	    }
	    
	    if ( statements[i].user_can_modify )
	    {
		active = preferred_foreground;
		if ( statements[i].plane == GifColourStatement.BACKGROUND )
		    active = preferred_background;
	    }
	    else
	    {
		active = f;
		if ( statements[i].plane == GifColourStatement.BACKGROUND )
		    active = b;
	    }
	    
	    for ( j=first; j<=last; j++ )
	    {
                // if the author can't change the colour but the user cam,
                // then we have to adjust the actual GIF colour entry 
                // against the reference background.  This could preserve
                // colour GIFs.  (Bit of a fudge because the reference
                // background is provided by the author but we assume that
                // it reflects the actual page background rather than the GIF
                // background and so is a good reference for deciding whether
                // the user wants the foreground adjusted.)
                if ( !statements[i].author_can_modify && statements[i].plane != GifColourStatement.BACKGROUND )
                {
                    gif_colour = new Color( 
                        ((int)colourbuf[(3*j)  ]) & 0xff, 
                        ((int)colourbuf[(3*j)+1]) & 0xff,
                        ((int)colourbuf[(3*j)+2]) & 0xff   );
                    active = colour_mapper.getPreferredForegroundColor( gif_colour );
                }
		colourbuf[(3*j)  ] = (byte)active.getRed();
		colourbuf[(3*j)+1] = (byte)active.getGreen();
		colourbuf[(3*j)+2] = (byte)active.getBlue();
	    }
	}

	out.write( colourbuf, 0, 3*count );
	
    }
    
    
}
