package com.tandbergtv.watchpoint.communication;

import java.util.Collection;

import com.tandbergtv.workflow.message.WorkflowMessage;

/**
 * Utitlity class for message handlers.
 * 
 * @author Raj Prakash
 */
public class Util {
	private static final String ZERO = "0";

	/*
	 * If no parameter found with the given name, returns null.
	 * If the value for the parameter is empty or blank, returns null.
	 */
	public static String getStringValueTrimmed(WorkflowMessage message, String paramName) {
		String value = (message.getPayload() != null) ? message.getValue(paramName) : null;
		if(value == null)
			return null;
		value = value.trim();
		if(value.length() == 0)
			return null;
		return value;
	}
	
	/*
	 * If no parameter found with the given name or the value of the parameter is empty/blank,
	 * returns null.
	 */
	public static Long getLongValue(WorkflowMessage message, String paramName) {
		String value = getStringValueTrimmed(message, paramName);
		return (value != null) ? Long.valueOf(value) : null;
	}
	
	/*
	 * If no parameter found with the given name or the value of the parameter is empty/blank,
	 * returns null.
	 */
	public static boolean getBooleanValue(WorkflowMessage message, String paramName) {
		String value = getStringValueTrimmed(message, paramName);
		return (value != null) ? Boolean.parseBoolean(value) : null;
	}

	/*
	 * Workflow work orders send numeric value zero to mean that value is unspecified.
	 * This method converts value < 1 to null. 
	 */
	public static Long convertZeroOrLessToNull(Long l) {
		return (l == null || l < 1) ? null : l;
	}

	public static String convertNullToZero(Long l) {
			return l == null ? ZERO : String.valueOf(l);
	}

	/*
	 * Validates that the given message contain all the given parameters.
	 * The value of parameters should be not empty and not blank.  
	 */
	public static void validateRequired(WorkflowMessage message, String... paramNames) {
		if(paramNames != null) {
			for(String paramName : paramNames) {
				if(getStringValueTrimmed(message, paramName) == null) {
					throw new RuntimeException("Parameter " + paramName +
							" is not found or does not have value");
				}
			}
		}
	}
	
	/*
	 * Gets comma-separated list of string value of the given collection.
	 */
	public static String getCommaSeparatedList(Collection<?> collection) {
		StringBuffer sb = new StringBuffer();
		if(collection != null) {
			boolean firstTime = true;
			for(Object object : collection) {
				if(firstTime) {
					firstTime = false;
				} else {
					sb.append(", ");
				}
				sb.append(object.toString());
			}
		}
		return sb.toString();
	}
}
