package com.armundia.core;

import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.serializer.JsonbSerializer;
import javax.json.bind.serializer.SerializationContext;
import javax.json.stream.JsonGenerator;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public class JsonbProvider implements ContextResolver<Jsonb> {

	private static final Logger log = Logger.getLogger(JsonbProvider.class.getName());

	private final Jsonb jsonB;

	public JsonbProvider() {
		log.log(Level.FINE, "JsonbProvider costruttore");

		JsonbConfig config = new JsonbConfig();

		config.setProperty(JsonbConfig.DATE_FORMAT, JsonbDateFormat.TIME_IN_MILLIS);
		log.log(Level.FINE, "WRITE_DATES_AS_TIMESTAMPS: true");
		config.withFormatting(false)
			.setProperty("jsonb.fail-on-unknown-properties", false)
			.withSerializers(new UUIDJsonbSerializer());
			//.withDeserializers(new WebSocketEventDeserializer());

		jsonB = JsonbBuilder.create(config);
	}

	@Override
	public Jsonb getContext(Class<?> objectType) {
		return jsonB;
	}

	public static class UUIDJsonbSerializer implements JsonbSerializer<UUID> {
		@Override
		public void serialize(UUID obj, JsonGenerator generator, SerializationContext ctx) {
			generator.write(obj.toString());
		}
	}

}
