/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scytl.products.ov.config.exceptions.specific.ConfigObjectMapperException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Adapter of jackson mapper to execute common transformations (from java to json, from json to java, from java to file
 * and from file to java)
 */
public class ConfigObjectMapper {

    private final ObjectMapper _mapper = new ObjectMapper();

    public String fromJavaToJSON(final Object obj) throws JsonProcessingException {

        return _mapper.writeValueAsString(obj);
    }

    public void fromJavaToJSONFile(final Object obj, final File dest) throws IOException {

        createFile(dest);

        _mapper.writerWithDefaultPrettyPrinter().writeValue(dest, obj);
    }

    public void fromJavaToJSONFileWithoutNull(final Object obj, final File dest) throws IOException {

        createFile(dest);

        _mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter().writeValue(dest, obj);
    }

    public <T> T fromJSONToJava(final String json, final Class<T> valueType) throws IOException {

        return _mapper.readValue(json, valueType);
    }

    public <T> T fromJSONFileToJava(final File src, final Class<T> valueType) throws IOException {
        return _mapper.readValue(src, valueType);
    }

    public <T> T fromJSONStreamToJava(final InputStream src, final Class<T> valueType) throws IOException {
        return _mapper.readValue(src, valueType);
    }

    private void createFile(final File dest) throws IOException {
		if (!dest.exists() && !dest.createNewFile()) {
			throw new ConfigObjectMapperException("An error occurred while creating the file  " + dest.toString());
		}
    }
}
