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

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jboss.seam.annotations.Logger;
import org.jboss.seam.log.Log;
import org.jboss.seam.web.LoggingFilter;

/**
 * @author Andrey Markavtsov
 *
 */
public class CopyImagesStuff implements ServletContextListener {
	
	static final String IMAGE_SRC = "/WEB-INF/Upload";
	
	static final String UPLOAD_ROOT_PARAMETER = "uploadRoot";
	
	
	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		try {
			String uploadFolderPath = sce.getServletContext().getRealPath(IMAGE_SRC);
			if (uploadFolderPath != null) {
				String uploadDest = sce.getServletContext().getInitParameter(UPLOAD_ROOT_PARAMETER);
				if (uploadDest == null) {
					throw new NullPointerException("UploadRoot was not defined");
				}
				
				File uploadFolder = new File(uploadFolderPath);
				File uploadDestFolder = new File(uploadDest);
				
				if (!uploadFolder.exists()) {
					throw new FileNotFoundException("Upload folder does not exists in " + IMAGE_SRC);
				}
				
				if (!uploadDestFolder.exists()) {
					uploadDestFolder.mkdirs();
				}
				
				CopyFile.copyDirectory(uploadFolder, uploadDestFolder);
			}
			
			
		}catch (Exception e) {
			System.out.println(e);
		}

	}

}
