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

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

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leonidrom
 */
public class YtCreateReplicaCommand extends YtCommandImpl.PostCommand<String> {
    private final YtPath tablePath;
    private final YtPath replicaPath;
    private YtNodeAttributes attributes;

    public YtCreateReplicaCommand(YtPath tablePath, YtPath replicaPath, YtNodeAttributes attributes) {
        if (attributes == null) {
            attributes = new YtNodeAttributes();
        }

        this.tablePath = tablePath;
        this.replicaPath = replicaPath;
        this.attributes = attributes;
    }

    @Override
    public UriComponentsBuilder createUri(URI proxyUri) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUri(proxyUri).path(API_V3 + "/create")
                .queryParam(PARAMETER_TYPE, "table_replica");
        return uri;
    }

    @Override
    protected Object getYtParameters() {
        Map<String, Object> attrsMap = new HashMap<>(attributes.getAttributes());
        attrsMap.put("table_path", tablePath.getPathWithoutCluster());
        attrsMap.put("replica_path", replicaPath.getPathWithoutCluster());
        attrsMap.put("cluster_name", replicaPath.getCluster());

        Map<String, Object> result = new HashMap<>();
        result.put("attributes", attrsMap);

        return result;
    }

    @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 boolean needHeavyProxy() {
        return false;
    }

    @Override
    public String toString() {
        return "CREATE REPLICA OF " + tablePath + " TO " + replicaPath;
    }
}
