package com.atlassian.stash.internal.json;

import com.atlassian.json.marshal.Jsonable;
import com.atlassian.json.marshal.JsonableMarshaller;
import com.atlassian.plugin.spring.AvailableToPlugins;
import com.atlassian.bitbucket.json.JsonRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Collections;

@Component
@AvailableToPlugins(JsonableMarshaller.class)
public class JsonRendererMarshaller implements JsonableMarshaller {

    private final JsonRenderer jsonRenderer;

    @Autowired
    public JsonRendererMarshaller(JsonRenderer jsonRenderer) {
        this.jsonRenderer = jsonRenderer;
    }

    @Override
    public Jsonable marshal(final Object object) {
        if (object instanceof Jsonable) {
            return (Jsonable) object;
        }
        return new Jsonable() {
            @Override
            public void write(Writer writer) throws IOException {
                // Use .append() instead of .write() so that the literal
                // string 'null' is written when the jsonRenderer returns null
                writer.append(jsonRenderer.render(object, Collections.<String, Object>emptyMap()));
            }
        };
    }

}
