package eu.dnetlib.functionality.modular.ui.workflows.objects;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.googlecode.sarasvati.NodeToken;

public class NodeTokenInfo {

	public class EnvParam {

		private String name;
		private String value;

		public EnvParam(final String name, final String value) {
			this.name = name;
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public String getValue() {
			return value;
		}
	}

	private String name;
	private long start;
	private long end;
	private List<EnvParam> params;

	public NodeTokenInfo(final String name) {
		super();
		this.name = name;
		this.start = 0;
		this.end = 0;
		this.params = Lists.newArrayList();
	}

	public NodeTokenInfo(final NodeToken token) {
		super();

		final Date start = token.getCreateDate();
		final Date end = token.getCompleteDate();

		this.name = token.getNode().getName();
		this.start = start == null ? 0 : start.getTime();
		this.end = end == null ? 0 : end.getTime();

		final Map<String, EnvParam> map = Maps.newHashMap();
		for (String name : token.getFullEnv().getAttributeNames()) {
			map.put(name, new EnvParam(name, token.getFullEnv().getAttribute(name)));
		}
		for (String name : token.getEnv().getAttributeNames()) {
			map.put(name, new EnvParam(name, token.getEnv().getAttribute(name)));
		}

		this.params = Lists.newArrayList(map.values());

		Collections.sort(this.params, new Comparator<EnvParam>() {

			@Override
			public int compare(final EnvParam o1, final EnvParam o2) {
				if (o1 == null) {
					return -1;
				} else if (o2 == null) {
					return 1;
				} else {
					return o1.getName().compareTo(o2.getName());
				}
			}
		});
	}

	public String getName() {
		return name;
	}

	public long getStart() {
		return start;
	}

	public long getEnd() {
		return end;
	}

	public List<EnvParam> getParams() {
		return params;
	}
}
