package gui;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;

public class ValidationUtil {

	public static boolean isNumber(String value) {
		return NumberUtils.isNumber(value);
	}

	/**
	 * Checks if an object is empty or null. Null part is especially important,
	 * since Java's built-in isEmpty() methods don't check for this condition
	 * and throw a nullPointerException as a result.
	 * <p>
	 * Supported structures:
	 * <ul>
	 * <li>String: empty if null or length is zero</li>
	 * <li>List: empty if null or size() == 0</li>
	 * <li>Map: empty if null or if it contains no keys, or if all keys map to an empty value </li>
	 * </ul>
	 */
	public static boolean isEmpty(Object o) {
		if (o == null) {
			return true;
		}

		if (o instanceof String) {
			if (((String) o).length() == 0) {
				return true;
			}
		}

		if (o instanceof List) {
			if (((List) o).isEmpty()) {
				return true;
			}
		}

		if (o instanceof Map) {
			if (((Map) o).keySet().isEmpty()) {
				return true;
			} else {
				for (Object val : ((Map) o).values()) {
					if (!isEmpty(val)) {
						// if map contains any value that isn't empty, the map isn't considered empty
						return false;
					}
				}
			}
		}

		return false;
	}

	public static boolean isNotEmpty(Object o) {
		return !isEmpty(o);
	}

	/**
	 * Checks whether a given File is a folder for which we have appropriate permission
	 */
	public static boolean isValidDirectory(File f) {
		return f.isDirectory() && f.canRead() && f.canWrite();
	}

	/**
	 * Checks whether a given File is a folder for which we have appropriate permission
	 */
	public static boolean isReadableDirectory(File f) {
		return f.isDirectory() && f.canRead();
	}
}
