package be.ac.ulb.code.wit.rangeparser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Range {
	private String tag;
	private Double quality = 1.0;
	private List<Parameter> mediaParameters = new ArrayList<Parameter>();
	private List<Parameter> acceptParameters = new ArrayList<Parameter>();
	
	private static final List<String> substitutions = new ArrayList<String>();
	static {
		substitutions.add("*");
	}

	public Collection<String> getSubstitutions() {
		return substitutions;
	}
	
	public String getTag() {
		return tag;
	}
	public Double getQuality() {
		return quality;
	}
	public List<Parameter> getMediaParameters() {
		return mediaParameters;
	}
	public List<Parameter> getAcceptParameters() {
		return acceptParameters;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(tag);
		
		for (Parameter p: mediaParameters) {
			sb.append(";" + p.toString());
		}
		if (acceptParameters.size() != 0) {
			StringBuilder sbAcceptParam = new StringBuilder();
			for (Parameter p: acceptParameters) {
				if (p.getKey().equals("q")) {
					sb.append(";" + p.toString());
				}
				else {
					sbAcceptParam.append(";" + p.toString());
				}
			}
			
			sb.append(sbAcceptParam);
		}
		
		return sb.toString();
	}
	
	
	private Double parseQuality() throws NumberFormatException {
		if (this.acceptParameters.size() == 0) {
			return 1.0;
		}
		
		Parameter p = acceptParameters.get(0);
		Double quality = Double.parseDouble(p.getValue());
		if (quality < 0.0) throw new NumberFormatException("Quality value out of bounds");
		if (quality > 1.0) throw new NumberFormatException("Quality value out of bounds");
		return quality;
	}
	
	public Range(String tag, List<Parameter> mediaParameters,
			List<Parameter> acceptParameters) throws NumberFormatException {
		super();
		this.tag = tag;
		this.mediaParameters = mediaParameters;
		this.acceptParameters = acceptParameters;
		this.quality = parseQuality();
	}
}
