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

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author aherman
 */
public class YtGetHeavyProxiesCommand extends YtCommandImpl.GetCommand<List<URI>> {
    private static final Logger log = LoggerFactory.getLogger(YtGetHeavyProxiesCommand.class);

    @Override
    protected UriComponentsBuilder createUri(URI proxyUri) {
        return UriComponentsBuilder.fromUri(proxyUri).path("/hosts");
    }

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

    @Override
    protected YtResult<List<URI>> onSuccess(YtStatus status, HttpResponse httpResponse) throws YtCommandException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            try {
                List<String> hosts = YtService.OM.readValue(entity.getContent(), new TypeReference<List<String>>(){});
                List<URI> result = new ArrayList<>(hosts.size());
                for (String host : hosts) {
                    try {
                        if (host.startsWith("http:") || host.startsWith("https:")) {
                            result.add(new URI(host));
                        } else {
                            result.add(new URI("http", host, "/", null));
                        }
                    } catch (URISyntaxException e) {
                        log.warn("Unable to create proxy URI: {}", host, e);
                    }
                }
                return YtResult.createResult(status, result);
            } catch (IOException e) {
                return YtResult.createError(status, "Unable read response", e);
            }
        } else {
            return YtResult.createResult(status, Collections.emptyList());
        }
    }
}
