/*

 ============================================================================
                   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 "Batik" 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. For more  information on the
 Apache Software Foundation, please see <http://www.apache.org/>.

*/

package org.apache.batik.ext.awt.g2d;

import java.awt.geom.AffineTransform;

/**
 * Contains a description of an elementary transform stack element,
 * such as a rotate or translate. A transform stack element has a
 * type and a value, which is an array of double values.<br>
 *
 * @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a>
 * @author <a href="mailto:paul_evenblij@compuware.com">Paul Evenblij</a>
 * @version $Id: TransformStackElement.java,v 1.5 2003/08/08 11:39:04 vhardy Exp $
 */
public abstract class TransformStackElement implements Cloneable{

    /**
     * Transform type
     */
    private TransformType type;

    /**
     * Value
     */
    private double transformParameters[];

    /**
     * @param type transform type
     * @param transformParameters parameters for transform
     */
    protected TransformStackElement(TransformType type,
                                    double transformParameters[]){
        this.type = type;
        this.transformParameters = transformParameters;
    }
    
    /**
     * @return an object which is a deep copy of this one
     */
    public Object clone() {
        TransformStackElement newElement = null;

        // start with a shallow copy to get our implementations right
        try {
            newElement = (TransformStackElement) super.clone();
        } catch(java.lang.CloneNotSupportedException ex) {}

        // now deep copy the parameter array
        double transformParameters[] = new double[this.transformParameters.length];
        System.arraycopy(this.transformParameters, 0, transformParameters, 0, transformParameters.length);
        newElement.transformParameters = transformParameters;
        return newElement;
    }

    /*
     * Factory methods
     */

    public static TransformStackElement createTranslateElement(double tx, 
                                                               double ty){
        return new TransformStackElement(TransformType.TRANSLATE, 
                                         new double[]{ tx, ty }) {
                boolean isIdentity(double[] parameters) {
                    return parameters[0] == 0 && parameters[1] == 0;
                }
            };
    }

    public static TransformStackElement createRotateElement(double theta){
        return new TransformStackElement(TransformType.ROTATE, 
                                         new double[]{ theta }) {
                boolean isIdentity(double[] parameters) {
                    return Math.cos(parameters[0]) == 1;
                }
            };
    }

    public static TransformStackElement createScaleElement(double scaleX, 
                                                           double scaleY){
        return new TransformStackElement(TransformType.SCALE, 
                                         new double[]{ scaleX, scaleY }) {
                boolean isIdentity(double[] parameters) {
                    return parameters[0] == 1 && parameters[1] == 1;
                }
            };
    }
    
    public static TransformStackElement createShearElement(double shearX, 
                                                           double shearY){
        return new TransformStackElement(TransformType.SHEAR, 
                                         new double[]{ shearX, shearY }) {
                boolean isIdentity(double[] parameters) {
                    return parameters[0] == 0 && parameters[1] == 0;
                }
            };
    }

    public static TransformStackElement createGeneralTransformElement
        (AffineTransform txf){
        double matrix[] = new double[6];
        txf.getMatrix(matrix);
        return new TransformStackElement(TransformType.GENERAL, matrix) {
                boolean isIdentity(double[] m) {
                    return (m[0] == 1 && m[2] == 0 && m[4] == 0 &&
                            m[1] == 0 && m[3] == 1 && m[5] == 0);
                }
            };
    }
    
    /**
     * Implementation should determine if the parameter list represents
     * an identity transform, for the instance transform type.
     */
    abstract boolean isIdentity(double[] parameters);
    
    /**
     * @return true iff this transform is the identity transform
     */
    public boolean isIdentity() {
        return isIdentity(transformParameters);
    }

    /**
     * @return array of values containing this transform element's parameters
     */
    public double[] getTransformParameters(){
        return transformParameters;
    }

    /**
     * @return this transform type
     */
    public TransformType getType(){
        return type;
    }

    /*
     * Concatenation utility. Requests this transform stack element
     * to concatenate with the input stack element. Only elements
     * of the same types are concatenated. For example, if this
     * element represents a translation, it will concatenate with
     * another translation, but not with any other kind of
     * stack element.
     * @param stackElement element to be concatenated with this one.
     * @return true if the input stackElement was concatenated with
     *         this one. False otherwise.
     */
    public boolean concatenate(TransformStackElement stackElement){
        boolean canConcatenate = false;

        if(type.toInt() == stackElement.type.toInt()){
            canConcatenate = true;
            switch(type.toInt()){
            case TransformType.TRANSFORM_TRANSLATE:
                transformParameters[0] += stackElement.transformParameters[0];
                transformParameters[1] += stackElement.transformParameters[1];
                break;
            case TransformType.TRANSFORM_ROTATE:
                transformParameters[0] += stackElement.transformParameters[0];
                break;
            case TransformType.TRANSFORM_SCALE:
                transformParameters[0] *= stackElement.transformParameters[0];
                transformParameters[1] *= stackElement.transformParameters[1];
                break;
            case TransformType.TRANSFORM_GENERAL:
                transformParameters 
                    = matrixMultiply(transformParameters, 
                                     stackElement.transformParameters);
                break;
            default:
                canConcatenate = false;
            }
        }

        return canConcatenate;
    }

    /**
     *  Multiplies two 2x3 matrices of double precision values
     */
    private double[] matrixMultiply(double[] matrix1, double[] matrix2) {
        double[] product = new double[6];
        AffineTransform transform1 = new AffineTransform(matrix1);
        transform1.concatenate(new AffineTransform(matrix2));
        transform1.getMatrix(product);
        return product;
    }

}
