package streetapp.service;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;

import streetapp.common.StreetAppInfo;
import streetapp.common.WLogger;
import streetapp.common.service.UsersService;

@Provider
public class HeaderFilter extends StreetAppService implements ContainerResponseFilter {
	private final WLogger log = WLogger.getLogger(this);

	@Context
	private ResourceInfo resourceInfo;

	@Override
	public void filter(ContainerRequestContext requestContext,
			ContainerResponseContext responseContext) throws IOException {
		log.debug("filter " + responseContext);
		boolean allow = false;

		String origin = requestContext.getHeaderString("Origin");
		if (origin == null) {
			allow = true;
			origin = "*";
		} else if (origin.indexOf("localhost") >= 0 && StreetAppInfo.isDevServer()) {
			allow = true;
			origin = "*";
		} else {
			String origins = this.getSettings().getParameter("header.allowed.origins", "default")
					.getValue();
			if (origins.indexOf(origin) >= 0) {
				allow = true;
			}
		}

		//
		log.debug("Filter origin " + origin + " allow " + allow);

		if (allow) {
			responseContext.getHeaders().add("Access-Control-Allow-Headers",
					"Content-type, " + UsersService.HEADER_AUTHENTICATION_TOKEN);

			responseContext.getHeaders().add("Access-Control-Allow-Origin", origin);
		}
	}

}
