package org.gcube.application.geoportal.utils;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.Collection;

import org.gcube.application.geoportal.model.Record;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public class Serialization {

static private ObjectMapper mapper;
static private ObjectMapper prettyMapper;
	
	static {
		mapper=new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
		mapper.registerModule(new JavaTimeModule());
//		mapper.setSerializationInclusion(Include.NON_NULL);
		
		
		prettyMapper=new ObjectMapper();
		prettyMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		prettyMapper.setSerializationInclusion(Include.NON_NULL);
		prettyMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
		prettyMapper.registerModule(new JavaTimeModule());
	}
	
	
	public static final <T extends Record> String asJSON(T toSerialize) throws JsonProcessingException {
		return mapper.writeValueAsString(toSerialize);
	}

	public static final <T extends Record> T readObject(String jsonString, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(jsonString, clazz);
	}
	
	
//	public static final String ISO_DATE_PATTERN="yyyyMMdd-kk:HH:mm:ss.SSS";
	
	public static final DateTimeFormatter FULL_FORMATTER=DateTimeFormatter.ofPattern("uuuuMMdd_HH-mm-ss");
	
	public static final String prettyPrint(Object toSerialize) throws JsonProcessingException {
		return prettyMapper.writeValueAsString(toSerialize);
	}
	
	
	
	// As DB String 
	
	public static String asString(Collection<?> coll) {
		if(coll==null||coll.isEmpty()) return "";
		StringBuilder builder=new StringBuilder();
		for(Object t : coll) {
			builder.append(t.toString() +",");
		}
		return builder.substring(0, builder.lastIndexOf(","));
	}
	
}
