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

import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpGet;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.List;

/**
 * @author aherman
 */
public abstract class YtAbstractReadTableCommand<T> extends YtCommandImpl.GetCommand<T> {
    private static final String ENCODING_SNAPPY = "y-snappy";

    protected final YtPath path;
    @Nullable
    protected final YtTableRange range;
    @Nullable
    protected final List<Object> keyValues;
    protected final OutputFormat outputFormat;
    protected final boolean compress;

    YtAbstractReadTableCommand(boolean compress, YtPath path, YtTableRange range, OutputFormat outputFormat) {
        this.compress = compress;
        this.path = path;
        this.range = range;
        this.keyValues = null;
        this.outputFormat = outputFormat;
    }

    public YtAbstractReadTableCommand(boolean compress, YtPath path, List<Object> keyValues, OutputFormat outputFormat) {
        this.compress = compress;
        this.path = path;
        this.range = null;
        this.keyValues = keyValues;
        this.outputFormat = outputFormat;
    }

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

    @Override
    protected void addHeaders(HttpGet request) {
        super.addHeaders(request);
        if (compress) {
            request.setHeader(HttpHeaders.ACCEPT_ENCODING, ENCODING_SNAPPY);
        }
    }

    @Override
    protected Object getYtParameters() {
        String readPath = path.toYtPath();
        if (range != null) {
            readPath = path.toYtPath(range);
        } else if (keyValues != null) {
            readPath = path.toYtPath(keyValues);
        }

        return new Params(readPath, outputFormat.getFormatYson());
    }

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

    private static class Params {
        @JsonProperty("path") public final String path;
        @JsonProperty("output_format") public final Object outputFormat;

        Params(String path, Object outputFormat) {
            this.path = path;
            this.outputFormat = outputFormat;
        }
    }
}