/**
 * DeleteAllFilesAction.java
 * Created on Jun 26, 2009
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.cms.action;

import java.io.File;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

/**
 * @author Vlada Jakobac
 * 
 */
public class DeleteAllFilesAction implements ActionHandler {

	private static final String ERROR_MESSAGE = "error-message";

	private static final String ALL_FILES_DELETED = "allFilesDeleted";

	private static final String UNDELETED_FILES_PATHS = "undeletedFilesPaths";

	private static final long serialVersionUID = -7693456999179074230L;

	private static final String LIST_OF_FILES = "listOfFiles";

	protected final Logger logger = Logger.getLogger(this.getClass());

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext
	 * )
	 */
	@Override
	public void execute(ExecutionContext context) throws Exception {

		String listOfFiles = getStringValue(context, LIST_OF_FILES);
		String[] fileArray = listOfFiles.split(",");

		String undeletedFilesPaths = "";

		if (fileArray != null){
			for (String url : fileArray) {
				if (!url.equals("")) {
					String undeletedFile = "";
					File physicalFile = new File(url);
					File physicalDirectory = physicalFile.getParentFile();
					try {
						if (!physicalFile.delete()) {
							undeletedFile = url;
							logger.error("Could not delete file: " + url);
						}
						logger.debug("Successfully deleted file: " + url);
					} catch (Throwable t) {
						undeletedFile = url;
					}
					// delete the directory if it's empty
					try {
						if (physicalDirectory.isDirectory()
							&& physicalDirectory.listFiles().length == 0)
							physicalDirectory.delete();
					} catch (Exception e) {//ignore the exception, because it's of no big importance
						
					}

					if (!undeletedFile.equals(""))
						undeletedFilesPaths = undeletedFilesPaths + undeletedFile
								+ ",";
				}
			}

		}
		if (undeletedFilesPaths.equals("")) {
			context.setVariable(ALL_FILES_DELETED, true);
		} else {
			context.setVariable(ALL_FILES_DELETED, false);
			context.setVariable(UNDELETED_FILES_PATHS, undeletedFilesPaths);
			context.setVariable(ERROR_MESSAGE, "Some files could not be deleted.");
		}

	}

	/*
	 * Return the value of a process variable as a string, irrespective of the
	 * variable type
	 */
	private String getStringValue(ExecutionContext context, String variableName) {
		Object value = context.getVariable(variableName);
		return (value == null) ? "" : value.toString();
	}
}
