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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.core.HttpContext;

public class Util {
	private static List<MediaType> SUPPORTED_MEDIAS;
	private static MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;

	static {
		SUPPORTED_MEDIAS = new ArrayList<MediaType>();
		SUPPORTED_MEDIAS.add(MediaType.APPLICATION_ATOM_XML_TYPE);
		SUPPORTED_MEDIAS.add(MediaType.APPLICATION_JSON_TYPE);

		Map<String, String> args;

		args = new HashMap<String, String>();
		args.put("type", "entry");
		SUPPORTED_MEDIAS.add(new MediaType("application", "atom+xml", args));

		args = new HashMap<String, String>();
		args.put("type", "feed");
		SUPPORTED_MEDIAS.add(new MediaType("application", "atom+xml", args));
	};

	public static MediaType getMediaIn(HttpContext context) {
		return context.getRequest().getMediaType();
	}

	public static MediaType getMediaOut(HttpContext context) {
		for (MediaType acceptable : context.getRequest()
				.getAcceptableMediaTypes()) {
			for (MediaType m : SUPPORTED_MEDIAS) {
				if (m.isCompatible(acceptable)) {
					return acceptable;
				}
			}
		}

		return DEFAULT_MEDIA_TYPE;
	}

}
