package com.atlassian.bitbucket.internal.ssh.json;

import com.atlassian.bitbucket.internal.key.ssh.rest.RestSshAccessKey;
import com.atlassian.bitbucket.internal.ssh.rest.RestSshKey;
import com.atlassian.bitbucket.json.JsonRenderer;
import com.atlassian.bitbucket.request.RequestManager;
import com.atlassian.bitbucket.rest.enrich.AvatarEnricher;
import com.atlassian.bitbucket.rest.enrich.LinkEnricher;
import com.atlassian.bitbucket.ssh.SshAccessKey;
import com.atlassian.bitbucket.ssh.SshKey;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import static com.atlassian.bitbucket.rest.util.RestUtils.makeAvatarRequest;

public class SshJsonRenderer implements JsonRenderer {

    private final AvatarEnricher avatarEnricher;
    private final LinkEnricher linkEnricher;
    private final JsonFactory jsonFactory;
    private final RequestManager requestManager;

    public SshJsonRenderer(AvatarEnricher avatarEnricher, LinkEnricher linkEnricher, RequestManager requestManager) {
        this.avatarEnricher = avatarEnricher;
        this.linkEnricher = linkEnricher;
        this.requestManager = requestManager;
        this.jsonFactory = new ObjectMapper().getJsonFactory();
    }

    @Override
    public String render(@Nullable Object object, @Nonnull Map<String, Object> options) {
        Object restSurrogate = null;
        if (object instanceof SshKey) {
            restSurrogate = new RestSshKey((SshKey) object);
        } else if (object instanceof SshAccessKey) {
            restSurrogate = new RestSshAccessKey((SshAccessKey) object);
        }

        if (restSurrogate != null) {
            avatarEnricher.enrich(restSurrogate, makeAvatarRequest(requestManager, options));
            linkEnricher.enrich(restSurrogate);
            StringWriter writer = new StringWriter();

            try (JsonGenerator generator = jsonFactory.createJsonGenerator(writer)) {
                generator.writeObject(restSurrogate);
                generator.flush();
                return writer.toString();
            } catch (IOException e) {
                // shouldn't happen
            }
        }
        return null;
    }
}
