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

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author aherman
 */
class YtStartTxCommand extends YtCommandImpl.PostCommand<String> {
    private final String cluster;
    private final int timeoutMs;
    private String parentTransactionId;

    public YtStartTxCommand(String cluster, int timeoutMs) {
        this.cluster = cluster;
        this.timeoutMs = timeoutMs;
    }

    public void setParentTransactionId(String parentTransactionId) {
        this.parentTransactionId = parentTransactionId;
    }

    @Override
    public UriComponentsBuilder createUri(URI proxyUri) {
        UriComponentsBuilder url = UriComponentsBuilder.fromUri(proxyUri).path(API_V3 + "/start_tx")
                .queryParam("timeout", timeoutMs);
        if (parentTransactionId != null) {
            url = url.queryParam(PARAMETER_TRANSACTION_ID, parentTransactionId);
        }
        return url;
    }

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

    @Override
    protected YtResult<String> onSuccess(YtStatus status, HttpResponse httpResponse) throws YtCommandException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity == null) {
            return YtResult.createError(status, "Response is empty", null);
        }
        try {
            String id = YtService.OM.readValue(EntityUtils.toString(entity), String.class);
            return YtResult.createResult(status, id);
        } catch (IOException e) {
            return YtResult.createError(status, "Unable to read response", e);
        }
    }

    @Override
    public String toString() {
        return "START_TX " + cluster;
    }
}
