package ru.yandex.webmaster3.storage.util.yt;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URI;

/**
 * @author avhaliullin
 */
class YtSetCommand extends YtCommandImpl.PutCommand<Void> {
    private static final ObjectMapper OM = new ObjectMapper();

    private final YtPath path;
    private final JsonNode data;

    YtSetCommand(YtPath path, JsonNode data) {
        this.path = path;
        this.data = data;
    }

    @Override
    public UriComponentsBuilder createUri(URI proxyUri) {
        return UriComponentsBuilder.fromUri(proxyUri).path(API_V3 + "/set")
                .queryParam(PARAMETER_PATH, this.path.toYtPath());
    }

    @Override
    public boolean needHeavyProxy() {
        return false;
    }

    @Override
    public String toString() {
        return "SET " + path;
    }

    @Override
    protected HttpEntity createRequestBody() {
        try {
            return new StringEntity(OM.writeValueAsString(data), ContentType.APPLICATION_JSON);
        } catch (IOException e) {
            throw new RuntimeException("Should never happen", e);
        }
    }
}
