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

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.JsonNode;
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 YtListCommand extends YtCommandImpl.GetCommand<List<YtPath>> {
    private final YtPath path;

    YtListCommand(YtPath path) {
        this.path = path;
    }

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

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

    @Override
    protected YtResult<List<YtPath>> onSuccess(YtStatus status, HttpResponse httpResponse) throws YtCommandException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity == null) {
            return YtResult.createError(status, "Response is empty", null);
        }
        try {
            JsonNode jsonNode = YtService.OM.readTree(EntityUtils.toString(entity));
            List<YtPath> nodes = YtJsonUtils.extractStringArray(jsonNode).stream()
                    .map(p -> YtPath.path(path, p))
                    .collect(Collectors.toList());
            return YtResult.createResult(status, nodes);
        } catch (IOException e) {
            return YtResult.createError(status, "Unable to read response", e);
        }
    }

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