/*
 * 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 nuts.core.image.ImageWrapper;
import nuts.core.image.Images;
import nuts.core.io.Files;
import nuts.core.io.VfsUtils;
import nuts.core.lang.Strings;

import java.io.IOException;

/**
 * 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 = Images.me().makeImage(data);
				String fm = Files.getFileNameExtension(getSaveName());
				if (Strings.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());

		VfsUtils.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) {
			VfsUtils.write(data, file);
		}
	}
}
