package eu.dnetlib.functionality.index.model.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import eu.dnetlib.functionality.index.model.Any;
import eu.dnetlib.functionality.index.model.AnyMap;
import eu.dnetlib.functionality.index.model.AnySeq;
import eu.dnetlib.functionality.index.model.DataFactory;
import eu.dnetlib.functionality.index.model.Value;
import eu.dnetlib.functionality.index.model.impl.DefaultDataFactoryImpl;

/**
 * utility class for handling / conversion of Any objects.
 *
 * Hint: The Any-to-JSON conversion for Date(Time)s is not symmetric. If the Any object contains Date(Time) values, they will be serialized
 * to String values in simple timestamp format. But when parsing JSON to an Any object, Date(Time) strings will not be recognized anymore,
 * but just read as String values.
 */
public class AnyUtil {

	/** Immutable empty AnyMap instance. */
	public static final AnyMap EMPTY_MAP = DefaultDataFactoryImpl.IMMUTABLE_EMPTY_MAP;

	/**
	 * prevent instance creation.
	 */
	protected AnyUtil() {
		// prevent instance creation
	}

	/**
	 * Converts an Any object into a native java object.
	 *
	 * @param any
	 *            the Any object
	 * @return a Pojo
	 */
	public static Object anyToNative(final Any any) {
		if (any.isMap()) {
			final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
			for (final Iterator<String> kIt = ((AnyMap) any).keySet().iterator(); kIt.hasNext();) {
				final String key = kIt.next();
				map.put(key, anyToNative(((AnyMap) any).get(key)));
			}
			return map;
		} else if (any.isSeq()) {
			final ArrayList<Object> list = new ArrayList<Object>();
			for (final Iterator<Any> aIt = any.iterator(); aIt.hasNext();) {
				final Any a = aIt.next();
				list.add(anyToNative(a));
			}
			return list;
		} else if (any.isString()) return ((Value) any).asString();
		else if (any.isLong()) return ((Value) any).asLong();
		else if (any.isDouble()) return ((Value) any).asDouble();
		else if (any.isBoolean()) return ((Value) any).asBoolean();
		else if (any.isDate()) return ((Value) any).asDate();
		else if (any.isDateTime()) return ((Value) any).asDateTime();
		else return ((Value) any).getObject();
	}

	/**
	 * Converts an object to an Any (recursively). The leaf object(s) must be convertable by {@link DataFactory#autoConvertValue(Object)}.
	 *
	 * @param object
	 *            The object to be converted. Supported (and tested in this order) are
	 *            <ul>
	 *            <li>{@code Map<String, Object>}
	 *            <li>{@code Collections<Object>}
	 *            <li>{@code Object[]}
	 *            <li>Any other object that can be {@link DataFactory#autoConvertValue(Object)}</li>
	 *            </ul>
	 *
	 * @return The converted Any
	 */
	@SuppressWarnings("unchecked")
	public static Any objectToAny(final Object object) {
		Any value = null;
		if (object instanceof Any) return (Any) object;
		else if (object instanceof Map<?, ?>) {
			value = mapToAny((Map<String, Object>) object);
		} else if (object instanceof Collection<?>) {
			value = collectionToAny((Collection<Object>) object);
		} else if (object.getClass().isArray()) {
			Object[] array = (Object[]) object;
			value = collectionToAny(Arrays.asList(array));
		} else {
			value = scalarObjectToAny(object);
		}
		return value;
	}

	/**
	 * Converts a collection to an AnySeq object.
	 *
	 * @param objects
	 *            The list of objects to convert.
	 * @return An AnySeq containing the objects as Any objects.
	 */
	private static AnySeq collectionToAny(final Collection<Object> objects) {
		AnySeq anySeq = null;
		if (objects != null) {
			anySeq = DataFactory.DEFAULT.createAnySeq();
			for (final Object obj : objects) {
				anySeq.add(objectToAny(obj));
			}
		}
		return anySeq;
	}

	/**
	 * Converts a scalar object to a Value object.
	 *
	 * @param obj
	 *            The object to convert.
	 * @return A Value representing the object.
	 */
	private static Any scalarObjectToAny(final Object obj) {
		return DataFactory.DEFAULT.autoConvertValue(obj);
	}

	/**
	 * Converts a map to an AnyMap object.
	 *
	 * @param map
	 *            The map (String to Object) to convert.
	 * @return An AnyMap representing the map with all Objects converted to Any.
	 */
	private static AnyMap mapToAny(final Map<String, Object> map) {
		AnyMap anyMap = null;
		if (map != null) {
			anyMap = DataFactory.DEFAULT.createAnyMap();
			for (final Entry<String, Object> entry : map.entrySet()) {
				anyMap.put(entry.getKey(), objectToAny(entry.getValue()));
			}
		}
		return anyMap;
	}

	/**
	 * get value for given path(list of keys) from AnyMap object. This methods throws no exception, if the path not exists an empty Any is
	 * the result.
	 *
	 * @param any
	 *            the Any object.
	 * @param path
	 *            path to the entry.
	 * @return value associated to the path.
	 */
	public static Any saveGet(final Any any, final String[] path) {
		if (path.length == 0) return DataFactory.DEFAULT.createAnyMap();
		try {
			Any current = any;
			for (final String key : path) {
				if (current.isMap()) {
					current = ((AnyMap) current).get(key);
				} else {
					current = null;
				}
			}
			if (current == null) return DataFactory.DEFAULT.createStringValue("undef");
			else return current;
		} catch (final Exception e) {
			return DataFactory.DEFAULT.createStringValue("undef");
		}
	}

	/**
	 * convert an exception to an any object.
	 *
	 * @param e
	 *            exception to convert
	 * @return any representation of exception
	 */
	public static AnyMap exceptionToAny(final Throwable e) {
		return exceptionToAny(e, new HashSet<String>());
	}

	/**
	 * convert an exception to an any object. stop in stacktrace printing when hitting known lines again.
	 *
	 * @param e
	 *            exception to convert
	 * @param visitedLines
	 *            lines that have been added to stacktraces before.
	 * @return any representation of exception
	 */
	private static AnyMap exceptionToAny(final Throwable e, final Collection<String> visitedLines) {
		final AnyMap any = DataFactory.DEFAULT.createAnyMap();
		any.put("type", e.getClass().getName());
		if (e.getMessage() != null) {
			any.put("message", e.getMessage());
		}
		final AnySeq st = DataFactory.DEFAULT.createAnySeq();
		for (final StackTraceElement stElement : e.getStackTrace()) {
			final String line = stElement.toString();
			st.add(line);
			if (!visitedLines.add(line)) {
				st.add("...");
				break;
			}
		}
		any.put("at", st);
		if ((e.getCause() != null) && (e.getCause() != e)) {
			any.put("causedBy", exceptionToAny(e.getCause(), visitedLines));
		}
		return any;
	}

	/**
	 * null save version.
	 */
	public static Double asDouble(final Any any) {
		return any == null ? null : any.asValue().asDouble();
	};

	/**
	 * null save version.
	 */
	public static Boolean asBoolean(final Any any) {
		return any == null ? null : any.asValue().asBoolean();
	};

	/**
	 * null save version.
	 */
	public static Date asDateTime(final Any any) {
		return any == null ? null : any.asValue().asDateTime();
	};

	/**
	 * null save version.
	 */
	public static Date asDate(final Any any) {
		return any == null ? null : any.asValue().asDate();
	};

	/**
	 * null save version.
	 */
	public static Long asLong(final Any any) {
		return any == null ? null : any.asValue().asLong();
	};

	/**
	 * null save version.
	 */
	public static String asString(final Any any) {
		return any == null ? null : any.asValue().asString();
	};

	/**
	 * null save version.
	 */
	public static AnyMap asMap(final Any any) {
		return any == null ? null : any.asMap();
	};

	/**
	 * null save version.
	 */
	public static AnySeq asSeq(final Any any) {
		return any == null ? null : any.asSeq();
	};

	/** convert AnyMap to java.util.Properties. */
	public static Properties anyToProperties(final AnyMap anyMap) {
		Properties props = new Properties();
		final Set<String> keySet = anyMap.keySet();
		for (final String key : keySet) {
			props.put(key, anyMap.get(key).toString());
		}
		return props;
	}

	/** convert java.util.Properties to AnyMap. */
	public static AnyMap propertiesToAny(final Properties props) {
		final AnyMap any = DataFactory.DEFAULT.createAnyMap();
		final Set<String> propNames = props.stringPropertyNames();
		for (final String prop : propNames) {
			any.put(prop, props.getProperty(prop));
		}
		return any;
	}

	/**
	 * returns the 1st map in the give SEQ that contains a value with the given name value, or null if not found.
	 *
	 * This is often useful for configs that are contained in a seq such as search filters.
	 *
	 * @since 1.1
	 */
	public static AnyMap findMapInSeq(final AnySeq seq, final String keyName, final String keyValue) {
		for (Any any : seq) {
			final String stringValue = any.asMap().getStringValue(keyName);
			if (keyValue.equals(stringValue)) return any.asMap();
		}
		return null;
	}
}
