/*
 * 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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;

public class VirtualFileItemFactory implements FileItemFactory {
	/**
	 * File System Manager
	 */
	private FileSystemManager fsManager;

	/**
	 * The directory in which uploaded files will be stored, if stored on disk.
	 */
	private FileObject repository;

	/**
	 * @param fsManager file system manager
	 * @param repository file repository
	 */
	public VirtualFileItemFactory(FileSystemManager fsManager, String repository) {
		try {
			if (fsManager == null) {
				this.fsManager = UploadManager.getFileSystemManager();
			}
			else {
				this.fsManager = fsManager;
			}

			if (repository == null) {
				this.repository = UploadManager.getRepository();
			}
			else {
				this.repository = this.fsManager.resolveFile(repository);
			}

			if (!this.repository.exists()) {
				this.repository.createFolder();
			}
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @return the fsManager
	 */
	public FileSystemManager getFsManager() {
		return fsManager;
	}

	/**
	 * @param fsManager the fsManager to set
	 */
	public void setFsManager(FileSystemManager fsManager) {
		this.fsManager = fsManager;
	}

	/**
	 * @return the repository
	 */
	public FileObject getRepository() {
		return repository;
	}

	/**
	 * @param repository the repository to set
	 */
	public void setRepository(FileObject repository) {
		this.repository = repository;
	}

	public FileItem createItem(String fieldName, String contentType,
			boolean isFormField, String fileName) {
		try {
			if (isFormField) {
				return new MemoryFileItem(fieldName, contentType,
						isFormField, fileName);
			}
			else {
				String uploadFileName = UploadManager.createUniqueFileName(fileName);
				FileObject fileObject = fsManager.resolveFile(repository, uploadFileName);
				return new VirtualFileItem(fieldName, contentType,
						isFormField, fileName, fileObject);
			}
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
