/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.gae.images;

import nuts.core.images.AbstractImageWrapper;
import nuts.core.images.ImageWrapper;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.OutputSettings;
import com.google.appengine.api.images.Transform;
import com.google.appengine.api.images.ImagesService.OutputEncoding;

/**
 */
public class GaeImageWrapper extends AbstractImageWrapper {
	private Image image;

	public GaeImageWrapper(Image image) {
		super();
		this.image = image;
		this.format = image.getFormat().toString();
	}

	/**
	 * @return the image
	 */
	public Image getImage() {
		return image;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(Image image) {
		this.image = image;
	}

	public byte[] getData() {
		return image.getImageData();
	}

	public int getWidth() {
		return image.getWidth();
	}

	public int getHeight() {
		return image.getHeight();
	}

	public ImageWrapper resize(int width, int height) {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();

		Transform resize = ImagesServiceFactory.makeResize(width, height);

		OutputEncoding oe;
		if ("jpg".equalsIgnoreCase(format) || "jpeg".equalsIgnoreCase(format)) {
			oe = OutputEncoding.JPEG;
		}
		else {
			oe = OutputEncoding.PNG;
		}
		OutputSettings oss = new OutputSettings(oe);
		oss.setQuality(quality);

		Image ni = imagesService.applyTransform(resize, image, oss);

		ImageWrapper iw = new GaeImageWrapper(ni);

		return iw;
	}

	public ImageWrapper resize(int scale) {
		int width = getWidth();
		int height = getHeight();

		if (width > height) {
			if (scale == width) {
				return this;
			}

			float ratio = (float)width / (float)height;
			width = scale;
			height = (int)(width / ratio);
		}
		else {
			if (scale == height) {
				return this;
			}

			float ratio = (float)height / (float)width;
			height = scale;
			width = (int)(height / ratio);
		}

		return resize(width, height);
	}

}
