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

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

import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author aherman
 */
class YtGetAttributesCommand extends YtCommandImpl.GetCommand<JsonNode> {
    private final YtPath path;

    YtGetAttributesCommand(YtPath path) {
        this.path = YtPath.path(path, "@");
    }

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

    @Override
    protected Object getYtParameters() {
        return new Parameters(path.toYtPath());
    }

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

    @Override
    protected YtResult<JsonNode> onSuccess(YtStatus status, HttpResponse httpResponse) throws YtCommandException {
        try {
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null) {
                return YtResult.createError(status, "Unable to read response", null);
            }
            try(InputStream content = entity.getContent()) {
                JsonNode jsonNode = YtService.OM.readTree(content);
                return YtResult.createResult(status, jsonNode);
            }
        } catch (IOException e) {
            return YtResult.createError(status, "Invalid json from YT", e);
        }
    }

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

    private static class Parameters {
        private final String path;

        public Parameters(String path) {
            this.path = path;
        }

        public String getPath() {
            return path;
        }
    }
}
