/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
package uk.ac.ic.doc.kevlar.core.programs.imageUtils;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Map;

import uk.ac.ic.doc.kevlar.api.programs.arguments.IArgumentInstance;
import uk.ac.ic.doc.kevlar.core.types.imageTypes.ImageTypeImpl;
import uk.ac.ic.doc.kevlar.publicInterfaces.AbstractProgram;
import uk.ac.ic.doc.kevlar.publicInterfaces.IImageType;
import uk.ac.ic.doc.kevlar.publicInterfaces.IInputPipe;
import uk.ac.ic.doc.kevlar.publicInterfaces.IOutputPipe;

public class ImageEdit extends AbstractProgram {

    private ImageEditScaler ies;
    private double angle;
    
    public void run(IArgumentInstance args, Map<String,IInputPipe> inputs, Map<String,IOutputPipe> outputs) {

        String operation = args.getSetValue("Operation");
        
        if( operation != null && operation.equals("Resize") ) {
            
            String width = args.getText("Width");
            String height = args.getText("Height");

            if( width == null && height == null ) {
                exit(1);
                return;
            }
            
            if( width == null ) {
                width = "";
            }
            
            if ( height == null ) {
                height = "";
            }
            
            ies = new ImageEditScaler(width,height);
            
        } else if (operation != null && operation.equals("Rotate")) {
            
            String angle = args.getSetValue("Angle");
            
            this.angle = Double.parseDouble(angle);
            
        } else {
            exit(1);
            return;
        }
        
        IInputPipe in = inputs.get("Images-In");
        IOutputPipe out = outputs.get("Images-Out");
        
        if( in == null || out == null ) {
            exit(0);    // no point doing anything.
            return;
        }
        
        try {
            while( true ) {
                
                IImageType img = (IImageType) in.read();
         System.err.println("Read an image");
                try {
                if( ies == null ) {
                    out.write(rotate(img));
                } else {
                    out.write(resize(img));
                }
                } catch ( IllegalArgumentException iae ) {
                }
            }
        } catch ( InterruptedException e ) {
            e.printStackTrace();
        } catch ( IllegalStateException ise ) {
            /* done */
        }
        
        /* and, we're done */
        exit(0);
    }
    
    
    private final double piConst = Math.PI / 180.0;
    
    private IImageType rotate( IImageType img ) {
        
        int type = img.getImage().getType();
        
        if( type == BufferedImage.TYPE_CUSTOM) {
            type = BufferedImage.TYPE_INT_RGB;
        }
        
        if( angle == 0 || angle == 180 ) {
            
            BufferedImage nimg = new BufferedImage(img.getImage().getWidth(),img.getImage().getHeight(),type);
            Graphics2D g = (Graphics2D) nimg.getGraphics();
            g.rotate( angle * piConst, nimg.getWidth()/2, nimg.getHeight()/2  );
            g.drawImage(img.getImage(),0,0,null);
            return new ImageTypeImpl(nimg);
        } else if ( angle == 90 || angle == 270 ) {
            BufferedImage nimg = new BufferedImage(img.getImage().getHeight(),img.getImage().getWidth(),type);
            Graphics2D g = (Graphics2D) nimg.getGraphics();
            g.rotate( angle * piConst, nimg.getWidth()/2, nimg.getHeight()/2 );
            g.drawImage(img.getImage(),0,0,null);
            return new ImageTypeImpl(nimg);
        } else {
            throw new IllegalArgumentException("Bad rotation angle");
        }
    }
    
    private IImageType resize( IImageType img ) {
        
        int type = img.getImage().getType();
        
        if( type == BufferedImage.TYPE_CUSTOM) {
            type = BufferedImage.TYPE_INT_RGB;
        }
        Dimension out = ies.getNewDimension(new Dimension(img.getImage().getWidth(),img.getImage().getHeight()));
        
        BufferedImage nimg = new BufferedImage(out.width,out.height,type);
        
        nimg.getGraphics().drawImage(img.getImage(),0,0,out.width,out.height,null);
        
        return new ImageTypeImpl(nimg);
    }
}
