package eu.dnetlib.broker.api;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ShortEventMessage implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 7302363775341307950L;

	private String eventId;

	private String originalId;

	private String title;

	private String topic;

	private float trust;

	private Map<String, String> message = new LinkedHashMap<>();

	public String getEventId() {
		return eventId;
	}

	public void setEventId(final String eventId) {
		this.eventId = eventId;
	}

	public String getOriginalId() {
		return originalId;
	}

	public void setOriginalId(final String originalId) {
		this.originalId = originalId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(final String title) {
		this.title = title;
	}

	public String getTopic() {
		return topic;
	}

	public void setTopic(final String topic) {
		this.topic = topic;
	}

	public float getTrust() {
		return trust;
	}

	public void setTrust(final float trust) {
		this.trust = trust;
	}

	public Map<String, String> getMessage() {
		return message;
	}

	public void setMessage(final Map<String, String> message) {
		this.message = message;
	}

	public void generateMessageFromObject(final Object bean) {
		this.message = generateMessageFromObject("", bean);
	}

	private static Map<String, String> generateMessageFromObject(final String prefix, final Object bean) {

		final Map<String, String> res = new LinkedHashMap<>();

		try {
			for (final PropertyDescriptor pd : Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors()) {
				if (pd.getReadMethod() != null) {
					final Object v = pd.getReadMethod().invoke(bean);
					if (v != null) {
						if (v instanceof List && !((List<?>) v).isEmpty()) {
							final List<?> list = (List<?>) v;
							for (int i = 0; i < list.size(); i++) {
								final Object x = list.get(i);
								if (x instanceof String && StringUtils.isNotBlank(x.toString())) {
									res.put(prefix + pd.getName() + "[" + i + "]", x.toString());
								} else {
									res.putAll(generateMessageFromObject(prefix + pd.getName() + "[" + i + "].", x));
								}
							}
						} else if (v instanceof String) {
							res.put(prefix + pd.getName(), v.toString());
						} else {
							res.putAll(generateMessageFromObject(pd.getName() + ".", v));
						}
					}
				}

			}

			return res;

		} catch (final Exception e) {
			return Collections.emptyMap();
		}

	}

}
