package nc.bs.hz.utils;

import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.*;

public class SafeObject {

	public SafeObject() {
	}

	public static boolean isNull(Object o) {
		return o == null || o.toString() == null
				|| o.toString().trim().length() == 0;
	}

	public static boolean isNotNull(Object o) {
		return !isNull(o);
	}

	public static UFDate toUFDate(Object o) {
		if (o instanceof UFDate)
			return (UFDate) o;
		if (isNotNull(o))
			return new UFDate(o.toString());
		else
			return null;
	}

	public static String toString(Object o) {
		if (o instanceof String)
			return (String) o;
		if (isNotNull(o))
			return o.toString();
		else
			return null;
	}

	public static String toString(CircularlyAccessibleValueObject vo,
			String attributeName) {
		return toString(vo.getAttributeValue(attributeName));
	}

	public static boolean toBool(Object o) {
		return toBoolean(o).booleanValue();
	}

	public static Boolean toBoolean(Object o) {
		if (o instanceof Boolean)
			return (Boolean) o;
		else
			return Boolean.valueOf(toUFBoolean(o).booleanValue());
	}

	public static UFBoolean toUFBoolean(Object o) {
		if (o instanceof UFBoolean)
			return (UFBoolean) o;
		if (isNull(o))
			return UFBoolean.valueOf(false);
		else
			return UFBoolean.valueOf(o.toString());
	}

	public static Double toDouble(Object o) {
		if (isNull(o))
			return Double.valueOf(0.0D);
		else
			return Double.valueOf(o.toString());
	}

	public static Integer toInteger(Object o) {
		if (o instanceof Integer)
			return (Integer) o;
		if (o instanceof UFDouble)
			return Integer.valueOf(((UFDouble) o).toDouble().intValue());
		if (isNull(o))
			return Integer.valueOf(0);
		else
			return Integer.valueOf(o.toString());
	}

	public static Integer toIntegerWithNull(Object o) {
		if (o instanceof Integer)
			return (Integer) o;
		if (isNull(o))
			return null;
		else
			return Integer.valueOf(o.toString());
	}

	public static UFDouble toUFDouble(Object o) {
		if (o instanceof UFDouble)
			return (UFDouble) o;
		if (isNull(o))
			return new UFDouble(0);
		else
			return new UFDouble(o.toString());
	}

	public static UFDouble toUFDoubleWithNull(Object o) {
		if (o instanceof UFDouble)
			return (UFDouble) o;
		if (isNull(o))
			return null;
		else
			return new UFDouble(o.toString());
	}

	public static UFDouble addUFDouble(Object d1, Object d2) {
		return (new UFDouble(toUFDouble(d1))).add(toUFDouble(d2));
	}
}
