
package eu.dnetlib.dhp.contextpropagation.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PropagationStructure implements Serializable {
	private Map<String, List<PropagationUse>> propagation = new HashMap<>();

	public Map<String, List<PropagationUse>> getPropagation() {
		return propagation;
	}

	public void add(String key, List<PropagationUse> value) {
		propagation.put(key, value);
	}

	public void setPropagation(Map<String, List<PropagationUse>> propagation) {
		this.propagation = propagation;
	}

	private void mergeList(PropagationUse use, List<PropagationUse> acc) {
		if (acc == null) {
			acc = new ArrayList<>();
		}
		for (PropagationUse pu : acc) {
			if (use.getUse().equals(pu.getUse())) {
				pu.getPath().addAll(use.getPath());
				if (Integer.valueOf(pu.getWeight()) < Integer.valueOf(use.getWeight())) {
					pu.setWeight(use.getWeight());
					return;
				}
			}
		}
		acc.add(use);
	}

	public PropagationStructure mergeFrom(PropagationStructure ps) {
		if (ps == null)
			return this;
		for (String key : ps.propagation.keySet()) {
			if (propagation.containsKey(key)) {
				ps.propagation.get(key).forEach(use -> mergeList(use, propagation.get(key)));
			} else {
				propagation
					.put(
						key,
						ps.propagation
							.get(key)
							.stream()
							.map(pu -> PropagationUse.copyInstance(pu))
							.collect(Collectors.toList()));
			}
		}
		return this;
	}

}
