/*

 ============================================================================
                   The Apache Software License, Version 1.1
 ============================================================================

 Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.

 Redistribution and use in source and binary forms, with or without modifica-
 tion, 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  acknowledgment:  "This product includes  software
    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
    Alternately, this  acknowledgment may  appear in the software itself,  if
    and wherever such third-party acknowledgments normally appear.

 4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
    used to  endorse or promote  products derived from  this software without
    prior written permission. For written permission, please contact
    apache@apache.org.

 5. Products  derived from this software may not  be called "Apache", nor may
    "Apache" appear  in their name,  without prior written permission  of the
    Apache Software Foundation.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
 APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
 DING, 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  consists of voluntary contributions made  by many individuals
 on  behalf of the Apache Software  Foundation and was  originally created by
 Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
 Software Foundation, please see <http://www.apache.org/>.

*/
package org.apache.cocoon.serialization;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.avalon.excalibur.pool.Poolable;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscodingHints;
import org.apache.batik.util.ParsedURL;
import org.apache.cocoon.Constants;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.components.transcoder.ExtendableTranscoderFactory;
import org.apache.cocoon.components.transcoder.TranscoderFactory;
import org.apache.cocoon.components.url.ParsedContextURLProtocolHandler;
import org.apache.cocoon.components.url.ParsedResourceURLProtocolHandler;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.sitemap.SitemapModelComponent;
import org.apache.cocoon.util.ClassUtils;
import org.apache.cocoon.xml.dom.SVGBuilder;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * A <a href="http://xml.apache.org/batik/">Batik</a> based Serializer for generating PNG/JPEG images
 *
 * @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a>
 * @author <a href="mailto:rossb@apache.org">Ross Burton</a>
 * @version CVS $Id: SVGSerializer.java,v 1.9 2003/10/09 15:26:54 sylvain Exp $
 */
public class SVGSerializer extends SVGBuilder
implements Composable, Serializer, Configurable, Poolable, CacheableProcessingComponent, Contextualizable, SitemapModelComponent {

    /**
     * Get the context
     */
    public void contextualize(Context context) throws ContextException {
        ParsedContextURLProtocolHandler.setContext(
            (org.apache.cocoon.environment.Context)context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT));
        ParsedURL.registerHandler(new ParsedContextURLProtocolHandler());
        ParsedURL.registerHandler(new ParsedResourceURLProtocolHandler());
    }

    /** The current <code>OutputStream</code>. */
    private OutputStream output;

    /** The current <code>mime-type</code>. */
    private String mimetype;

    /** The current <code>Transcoder</code>.  */
    Transcoder transcoder;

    /** The Transcoder Factory to use */
    TranscoderFactory factory = ExtendableTranscoderFactory.getTranscoderFactoryImplementation();
    
    /** The current caching key */
    private Serializable cachingKey;
    
    /** The default Batik <code>TranscodingHints</code> set up in configuration step */
    private TranscodingHints defaultTranscodingHints;
    
    /** The current Batik <code>TranscodingHints</code> can overrides the default one */
    private TranscodingHints currentTranscodingHints;
    
    /** The map holding information for the Batik <code>TranscodingHints.Key</code>s */
    private Map transcodingHintKeysInfo;
    
    /** Override default <code>TranscodingHints</code> with sitemap parameters? */
    private boolean overrideTranscodingHints = false;
    private boolean _overrideTranscodingHints = false;
    /**
     * Set the <code>OutputStream</code> where the XML should be serialized.
     */
    public void setOutputStream(OutputStream out) {
        this.output = out;
    }

    /**
     * Set the configurations for this serializer.
     */
    public void configure(Configuration conf) throws ConfigurationException {
        this.mimetype = conf.getAttribute("mime-type");
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("mime-type: " + mimetype);
        }

        // Using the Transcoder Factory, get the default transcoder
        // for this MIME type.
        this.transcoder = factory.createTranscoder(mimetype);

        // Iterate through the parameters, looking for a transcoder reference
        Configuration[] parameters = conf.getChildren("parameter");
        for (int i = 0; i < parameters.length; i++) {
            String name = parameters[i].getAttribute("name");
            if ("transcoder".equals(name)) {
                String transcoderName = parameters[i].getAttribute("value");
                try {
                    this.transcoder = (Transcoder)ClassUtils.newInstance(transcoderName);
                } catch (Exception ex) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Cannot load  class " + transcoderName, ex);
                    }
                    throw new ConfigurationException("Cannot load class " + transcoderName, ex);
                }
            }
        }
        // Do we have a transcoder yet?
        if (this.transcoder == null ) {
            throw new ConfigurationException(
                "Could not autodetect transcoder for SVGSerializer and "
                + "no transcoder was specified in the sitemap configuration."
            );
        }

        // Now run through the other parameters, adding them to the 
        // default transcoding hints
        defaultTranscodingHints = new TranscodingHints();
        transcodingHintKeysInfo = new HashMap();
        for (int i = 0; i < parameters.length; i++ ) {
            String name = parameters[i].getAttribute("name");
            // Skip over the parameters we've dealt with. Ensure this
            // is kept in sync with the above list!
            if ("transcoder".equals(name)) {
                continue;
            }

            // Now try and get the hints out
            try {
                String batikKeyName = "KEY_" + name.toUpperCase();
                String batikKeyType = parameters[i].getAttribute("type", "STRING").toUpperCase();
                //Use reflection to get a reference to the key object
                TranscodingHints.Key key = (TranscodingHints.Key) (this.transcoder.getClass().getField(batikKeyName).get(this.transcoder));
                
                //The value is not required. It can only declares a default value for a key
                Object value = computeBatikKeyValue(batikKeyType, parameters[i].getAttribute("value", null));
                
                // Adding transcoding hint value
                if (value != null) {
                    if(getLogger().isDebugEnabled()) {
                        getLogger().debug("Adding default hint \"" + name + "\" with value \"" + value.toString() + "\"");
                    }
                    defaultTranscodingHints.put(key, value);
                }
                
                // Adding info for all declared keys 
                TranscodingHintKeyInfo keyInfo = new TranscodingHintKeyInfo(batikKeyName, batikKeyType, key);
                transcodingHintKeysInfo.put(name, keyInfo);
                
            } catch (ClassCastException ex) {
                // This is only thrown from the String keyType... line
                throw new ConfigurationException("Specified key (" + name + ") is not a valid Batik Transcoder key.", ex);
            } catch (IllegalAccessException ex) {
                throw new ConfigurationException("Cannot access the key for parameter \"" + name + "\"", ex);
            } catch (NoSuchFieldException ex) {
                throw new ConfigurationException("No field available for parameter \"" + name + "\"", ex);
            }
        }
        
        // Setting default value to enable overriding default transcoding hints
        overrideTranscodingHints =
            conf.getChild("override-transcoding-hints").getValueAsBoolean(false);
        if (getLogger().isDebugEnabled() && overrideTranscodingHints) {
            getLogger().debug(
                "The transcoding hints may be overrinden by sitemap parameters");
        }
    }
    
    /**
     * Set the <code>SourceResolver</code>, the <code>Map</code> with
     * the object model, the source and sitemap
     * <code>Parameters</code> used to process the request.
     */
    public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException {
        currentTranscodingHints = (TranscodingHints) defaultTranscodingHints.clone();
        cachingKey = "1";
        // Overrides configured batik transcoding hints values with sitemap parameters?
        this._overrideTranscodingHints = par.getParameterAsBoolean("override-transcoding-hints", overrideTranscodingHints);
        if (this._overrideTranscodingHints) {
            StringBuffer cachingKeyBuffer = new StringBuffer();
            Set entries = transcodingHintKeysInfo.entrySet();
            // Looking for sitemap parameters we have the batik keys info
            for(Iterator i=entries.iterator(); i.hasNext();) {
                Map.Entry entry = (Map.Entry) i.next();
                String keyName = (String) entry.getKey();
                // Any sitemap parameter ? 
                String keyValue = par.getParameter(keyName, null);
                if (keyValue != null) {
                    TranscodingHintKeyInfo keyInfo = (TranscodingHintKeyInfo) entry.getValue();
                    String batikKeyName = keyInfo.getName();
                    String batikKeyType = keyInfo.getType();
                    TranscodingHints.Key batikKey = keyInfo.getTranscodingHintKey();
                    Object batikKeyValue =
                        computeBatikKeyValue(batikKeyType, keyValue);
                    if (batikKeyValue == null) {
                        getLogger().info("Cannot compute value for parameter \"" + keyName + "\" (" +batikKeyName + "). If a default value was set, it will be used instead.");
                    } else {
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug("Setting parameter \"" + keyName + "\" (" + batikKeyName + ") value to " + batikKeyValue.toString());
                        }
                        currentTranscodingHints.put(batikKey, batikKeyValue);
                        cachingKeyBuffer.append(";");
                        cachingKeyBuffer.append(keyName);
                        cachingKeyBuffer.append("=");
                        cachingKeyBuffer.append(keyValue);
                    }                    
                }
                
            }
            // Set the caching key
            String currentCachingKey = cachingKeyBuffer.toString().trim();
            if (currentCachingKey.length() > 0) {
                cachingKey = currentCachingKey;
            }            
        }
        
    }

    /**
     * Set the current <code>ComponentManager</code> instance used by this
     * <code>Composable</code>.
     */
    public void compose(ComponentManager manager) {
    }

    /**
     * Receive notification of a successfully completed DOM tree generation.
     */
    public void notify(Document doc) throws SAXException {
        try {
            TranscoderInput transInput = new TranscoderInput(doc);

            // Buffering is done by the pipeline (See shouldSetContentLength)
            TranscoderOutput transOutput = new TranscoderOutput(this.output);
            // Setting current transcoding hints to transcoder
            transcoder.setTranscodingHints(currentTranscodingHints);
            transcoder.transcode(transInput, transOutput);
        } catch (TranscoderException ex) {
            if (ex.getException() != null) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Got transcoder exception writing image, rethrowing nested exception", ex);
                }
                throw new SAXException("Exception writing image", ex.getException());
            }

            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Got transcoder exception writing image, rethrowing", ex);
            }
            throw new SAXException("Exception writing image", ex);
        } catch (Exception ex) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Got exception writing image, rethrowing", ex);
            }
            throw new SAXException("Exception writing image", ex);
        }
    }

    /**
     * Return the MIME type.
     */
    public String getMimeType() {
        return mimetype;
    }

    /**
     * Generate the unique key.
     * This key must be unique inside the space of this component.
     * This method must be invoked before the getValidity() method.
     *
     * @return The generated key or <code>0</code> if the component
     *              is currently not cacheable.
     */
    public Serializable getKey() {
        return cachingKey;
    }

    /**
     * Generate the validity object.
     * Before this method can be invoked the getKey() method
     * must be invoked.
     *
     * @return The generated validity object or <code>null</code> if the
     *         component is currently not cacheable.
     */
    public SourceValidity getValidity() {
        return NOPValidity.SHARED_INSTANCE;
    }

    /**
     * Returns true so the pipeline implementation will buffer generated
     * output and write content length to the response.
     * <p>Batik's PNGTranscoder closes the output stream, therefore we
     * cannot pass the output stream directly to Batik and have to
     * instruct pipeline to buffer it. If we do not buffer, we would get
     * an exception when {@link org.apache.cocoon.Cocoon#process}
     * tries to close the stream.
     */
    public boolean shouldSetContentLength() {
        return true;
    }
    
    /**
     * Computes the transcoding hint value for a key type declared in 
     * the configuration of this serializer. 
     * 
     * @param keyType The key type.
     * @param value The string value to be converted into an object.
     * @return The object value. it will return null if the value
     *         cannot be computed or the key type is unknown.
     */
    private Object computeBatikKeyValue(String type, String value) {
        if (value == null) {
            return null;
        }
        if ("STRING".equals(type)) {
            return value;
        }
        if (value.length() == 0) {
            return null;
        }
        if ("FLOAT".equals(type)) {
            try {
                return Float.valueOf(value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        if ("INTEGER".equals(type)) {

            try {
                return Integer.valueOf(value);
            } catch (NumberFormatException e) {
                return null;
            }

        }
        if ("BOOLEAN".equals(type)) {
            return Boolean.valueOf(value);
        }
        if ("COLOR".equals(type)) {
            // Can throw an exception
            if (value.startsWith("#")) {
                value = value.substring(1);
            }
            try {
                return new Color(Integer.parseInt(value, 16));
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
    
    /**
     * This is a convinience class to hold information on the configured 
     * Batik keys  
     */
    private static final class TranscodingHintKeyInfo {

        /** key type as of INTEGER, ... */
        private String type;

        /** batik key name starting with KEY_ */
        private String name;

        /** batik <code>TranscodingHints.Key</code> */
        private TranscodingHints.Key key;

        /**
         * Constructor
         * 
         * @param name The batik key name
         * @param type The configured key type
         * @param batikKey The <code>TranscodingHints.Key</code> 
         */
        public TranscodingHintKeyInfo(
            String name,
            String type,
            TranscodingHints.Key batikKey){
            this.name = name;
            this.type = type;
            this.key = batikKey;
          
        }
        
        /**
         * Gets the batik key name
         * 
         * @return The batik key name
         */
        public String getName() {
            return name;
        }

        /**
         * Gets the configured key type
         * 
         * @return The key type
         */
        public String getType() {
            return type;
        }

        /**
         * Gets the <code>TranscodingHints.Key</code>
         * 
         * @return The <code>TranscodingHints.Key</code>
         */
        public TranscodingHints.Key getTranscodingHintKey() {
            return key;
        }

    }


}
