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

import com.fasterxml.jackson.annotation.JsonProperty;
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.Collection;

/**
 * @author leonidrom
 */
public class YtEraseCommand extends YtCommandImpl.PostCommand<YtOperationId> {
    private final YtPath table;
    private final Collection<YtTableRange> rowRanges;

    public YtEraseCommand(YtPath table, Collection<YtTableRange> rowRanges) {
        this.table = table;
        this.rowRanges = rowRanges;
    }

    @Override
    public UriComponentsBuilder createUri(URI proxyUri) {
        return UriComponentsBuilder.fromUri(proxyUri)
                .path(API_V3 + "/erase");
    }

    @Override
    protected Object getYtParameters() {
        Spec spec = new Spec(table.toYtPath(rowRanges));
        return new Parameters(spec);
    }

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

    @Override
    public String toString() {
        return "ERASE " + table.toYtPath(rowRanges);
    }

    @Override
    protected YtResult<YtOperationId> 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 = EntityUtils.toString(entity);
            String operationId = YtService.OM.readValue(id, String.class);
            return YtResult.createResult(status, new YtOperationId(table.getCluster(), operationId));
        } catch (IOException e) {
            return YtResult.createError(status, "Unable to read response", e);
        }
    }

    private static class Spec {
        @JsonProperty("table_path")
        public final String tablePath;

        public Spec(String tablePath) {
            this.tablePath = tablePath;
        }
    }

    private static class Parameters {
        @JsonProperty("spec")
        public final Spec spec;

        Parameters(Spec spec) {
            this.spec = spec;
        }
    }
}
