package cz.muni.fi.lasaris.sbms.data.api.request;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

import cz.muni.fi.lasaris.sbms.data.entities.Address;

public class GroupedSnapshotRequest {
	private Map<String, List<Address>> groups;

	public Map<String, List<Address>> getGroups() {
		return groups;
	}

	public void setGroups(Map<String, List<Address>> groups) {
		this.groups = groups;
	}
	
	/*
	@JsonIgnore
	public List<AddressGroup> getReadSpecs() {
		List<AddressGroup> result = new ArrayList<AddressGroup>(groups.size());
		for(String key : groups.keySet()) {
			AddressGroup g = new AddressGroup(groups.get(key), key);
		}
		return result;
	}
	*/
	
	public NavigableMap<String, GroupedSnapshotRequest> getProtocols() {
		NavigableMap<String, GroupedSnapshotRequest> result = new TreeMap<String, GroupedSnapshotRequest>();
		for(String group : groups.keySet()) {
			for(Address a : groups.get(group)) {
				String p = a.getProtocol();
				if(p == null) {
					// TreeMap does not allow null keys
					p = "";
				}
				if(!result.containsKey(p)) {
					result.put(p, null);
				}
			}
		}
		
		// we suppose in most cases the data sources won't be mixed
		// therefore we decided to go with this two-phase process that saves the creation of a new structures
		// when not needed
		if(result.size() == 1) {
			result.put(result.firstKey(), this);
			return result;
		}
		
		for(String group : groups.keySet()) {
			for(Address a : groups.get(group)) {
				String p = a.getProtocol();
				if(p == null) {
					// TreeMap does not allow null keys
					p = "";
				}
				GroupedSnapshotRequest g = result.get(p);
				if(g == null) {
					g = new GroupedSnapshotRequest();
					g.setGroups(new LinkedHashMap<String, List<Address>>());
					result.put(p, g);
				} 
				if(!g.getGroups().containsKey(group)) {
					g.getGroups().put(group, new LinkedList<Address>());
				}
				g.getGroups().get(group).add(a);	
			}
		}
		
		return result;
		
	}
}
