/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 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.exts.fileupload;

import java.io.IOException;

import nuts.core.images.ImageFactory;
import nuts.core.images.ImageWrapper;
import nuts.core.io.IOUtils;
import nuts.core.lang.StringUtils;

/**
 * Upload Image Bean Object
 */
@SuppressWarnings("serial")
public class UploadImage extends UploadFile {

	private ImageWrapper image;
	
	/**
	 * constructor
	 */
	public UploadImage() {
		setContentType("image");
	}

	/**
	 * @return the image
	 * @throws IOException if an I/O error occurs
	 */
	public ImageWrapper getImage() throws Exception {
		if (image == null) {
			byte[] data = getData();
			if (data != null) {
				image = ImageFactory.getInstance().makeImage(data);
				String fm = IOUtils.getFileNameExtension(getSaveName());
				if (StringUtils.isNotEmpty(fm)) {
					image.setFormat(fm);
				}
			}
		}
		return image;
	}

	/**
	 * resize the image
	 * @param scale scale
	 * @throws Exception if an error occurs
	 */
	public void resize(int scale) throws Exception {
		ImageWrapper img = getImage();
		if (img == null) {
			return;
		}

		image = img.resize(scale);

		data = image.getData();

		newFile("r." + image.getFormat());

		IOUtils.write(data, file);
	}

	/**
	 * resize the image
	 * @param width width
	 * @param height height
	 * @throws Exception if an error occurs
	 */
	public void resize(int width, int height) throws Exception {
		ImageWrapper img = getImage();
		if (img == null) {
			return;
		}

		image = img.resize(width, height);

		data = image.getData();

		if (file != null) {
			IOUtils.write(data, file);
		}
	}
}
