package com.armundia.app.utilities.rest;

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.serializer.JsonbSerializer;
import javax.json.bind.serializer.SerializationContext;
import javax.json.stream.JsonGenerator;


public class JsonbUtils {
    private static Logger log = Logger.getLogger(JsonbUtils.class.getName());

	public static <T> T fromJson(String json, Class<T> objClass) {
		if (json == null) 
			return null;
		
		try {
			T o = getMapper().fromJson(json, objClass);
			return o;
		} catch (Exception var3) {
			var3.printStackTrace();
			return null;
		}
	}

	public String toJson(Object o, boolean test) {
		if (o == null) {
			return null;
		} else {
			String out = toJson(o);
			if (test) {
				o = fromJson(out, o.getClass());
				String out1 = toJson(o);
				if (!out.equals(out1)) {
					log.severe("Errore conversione");
					log.severe("out=" + out);
					log.severe("out1=" + out1);
				}
			}

			return out;
		}
	}

	public static String toJson(Object o) {
		if (o == null) {
			return null;
		} else {
			String ret = "Error";

			try {
				ret = getMapper().toJson(o);
			} catch (Exception var3) {
				var3.printStackTrace();
			}

			return ret;
		}
	}

	public static String toJsonPretty(Object o) {
		if (o == null) {
			return null;
		} else {
			String ret = "Error";

			try {
				Jsonb mapper = getMapper(true);
				ret = mapper.toJson(o);
			} catch (Exception e) {
				log.log(Level.SEVERE, "Error during toJsonPretty", e);
			}

			return ret;
		}
	}
	
	public static <T> T reconvert(Object obj, Class<T> targetClass) {
		String json = toJson(obj);
		return fromJson(json, targetClass);
	}

	private static Jsonb getMapper() {
		return getMapper(false);
	}

	private static Jsonb getMapper(boolean pretty) {
		JsonbConfig config = new JsonbConfig();
		config.setProperty("jsonb.date-format", "##time-in-millis");
		config.withFormatting(pretty).withSerializers(new JsonbSerializer[]{new UUIDJsonbSerializer()});
		Jsonb jsonb = JsonbBuilder.create(config);
		return jsonb;
	}

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