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

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

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

public class SnapshotRequest {
	private List<Address> addresses;

	public List<Address> getAddresses() {
		return addresses;
	}

	public void setAddresses(List<Address> addresses) {
		this.addresses = addresses;
	}
	
	public NavigableMap<String, SnapshotRequest> getProtocols() {
		NavigableMap<String, SnapshotRequest> result = new TreeMap<String, SnapshotRequest>();
		for(Address a : addresses) {
			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(Address a : addresses) {
			String p = a.getProtocol();
			if(p == null) {
				// TreeMap does not allow null keys
				p = "";
			}
			SnapshotRequest g = result.get(p);
			if(g == null) {
				g = new SnapshotRequest();
				g.setAddresses(new LinkedList<Address>());
				result.put(p, g);
			} 
			g.getAddresses().add(a);	
		}

		return result;
	}
	
	@Override
	public String toString() {
		return "SnapshotRequest [addresses=" + addresses + "]";
	}
	
	
}
