package ru.yandex.qe.dispenser.ws.goal;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.bolts.collection.Cf;
import ru.yandex.bolts.collection.IteratorF;
import ru.yandex.bolts.collection.ListF;
import ru.yandex.startrek.client.AuthenticatingStartrekClient;
import ru.yandex.startrek.client.PageIterator;
import ru.yandex.startrek.client.Session;
import ru.yandex.startrek.client.StartrekClientBuilder;
import ru.yandex.startrek.client.model.SearchRequest;
import ru.yandex.startrek.client.utils.UriBuilder;

@Component
public class TrackerGoalClientImpl implements TrackerGoalClient {

    private final Session trackerSession;
    private final String trackerQueue;

    @Inject
    public TrackerGoalClientImpl(@Value("${goal.tracker.client.max.connections}") final int trackerMaxConnections,
                                 @Value("${goal.tracker.client.connection.timeout.seconds}") final long trackerConnectionTimeoutSeconds,
                                 @Value("${goal.tracker.client.socket.timeout.milliseconds}") final long trackerSocketTimeoutMilliseconds,
                                 @Value("${tracker.oauth.token}") final String trackerToken,
                                 @Value("${tracker.service.url}") final String trackerBaseUrl,
                                 @Value("${goal.tracker.queue}") final String trackerQueue) {

        trackerSession = StartrekClientBuilder.newBuilder()
                .uri(trackerBaseUrl)
                .maxConnections(trackerMaxConnections)
                .connectionTimeout(trackerConnectionTimeoutSeconds, TimeUnit.SECONDS)
                .socketTimeout(trackerSocketTimeoutMilliseconds, TimeUnit.MILLISECONDS)
                .userAgent("Dispenser")
                .build(trackerToken);

        this.trackerQueue = trackerQueue;
    }

    @Override
    public IteratorF<GoalIssue> findGoalIssues() {

        final ListF<String> fields = Cf.list("key", "summary", "goalImportance", "status");
        final ListF<String> expands = Cf.list("locallinkrefs");

        final SearchRequest query = SearchRequest.builder().queue(trackerQueue)
                .fields(fields.toArray(String.class)).build();

        final AuthenticatingStartrekClient client = (AuthenticatingStartrekClient) trackerSession;

        final UriBuilder uriBuilder = UriBuilder.cons(client.getEndpoint()).appendPath("issues")
                .appendPath("_search").addParam("fields", fields.mkString(","));

        expands.forEach(expand -> uriBuilder.addParam("expand", expand));

        return new PageIterator<>(uriBuilder.build(), next -> client.doPost(next, query,
                client.factory().page(GoalIssue.class)));
    }
}
