/**
 * 
 */
package org.richfaces.realworld.startup;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.richfaces.realworld.util.FileUtils;


/**
 * @author Andrey Markavtsov
 *
 */

@Name("CopyImagesStuff")
@Scope(ScopeType.APPLICATION)
@Startup
public class CopyImageStuff {
	
	static final String WEB_INF = "WEB-INF";
	
	static final String IMAGE_FOLDER = "/Upload";
	
	//TODO nick - change constant value to include "richfaces"
	static final String REALWORLD_FOLDER = "realworld";
	
	@Out(scope = ScopeType.APPLICATION)
	File uploadRoot;
	
	@Out(scope = ScopeType.APPLICATION)
	String uploadRootPath;
	
	String imageSrc;
	
	@Create
	public void create() throws Exception {
		resolveImageFolder();
		resolveUploadRoot();
		
		copyImages();
	}
	
	@Destroy
	public void destroy()throws IOException {
		//TODO nick - delete even data is stored in DB?
		FileUtils.deleteDirectory(uploadRoot);
	}
	
	
	void resolveImageFolder() {
		//TODO nick - what this cast is for?
		URLClassLoader loader = (URLClassLoader)getClass().getClassLoader();
		//TODO nick - rewrite that
		URL path = loader.getResource("");
		String classLoadPath = null;
		String realPath = null;
		
		if (path != null) {
			classLoadPath = path.getFile();
		}
		
		if (classLoadPath != null) {
			int index = classLoadPath.indexOf(WEB_INF);
			if (index != -1) {
				realPath = classLoadPath.substring(0, index + WEB_INF.length()) + IMAGE_FOLDER;
			}
		}
		
		if (realPath != null) {
			this.imageSrc = realPath;
		}else {
			throw new NullPointerException("Cannot bound image folder path");
		}

	}
	
	void resolveUploadRoot()throws IOException {
		String uploadRootPath = System.getProperty("java.io.tmpdir") + REALWORLD_FOLDER + File.separator;
		if (uploadRootPath != null) {
			uploadRoot = new File(uploadRootPath);
			if (uploadRoot.exists()) {
				FileUtils.deleteDirectory(uploadRoot);
			}
			uploadRoot.mkdir();
			this.uploadRootPath = uploadRoot.getCanonicalPath();
		}else {
			throw new NullPointerException("Upload root was not created");
		}
	}
	
	
	void copyImages()throws IOException {
		FileUtils.copyDirectory(new File(imageSrc), uploadRoot);
	}

	

}
