package cz.moneta.test.dsl.elastic.tasks;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.util.TestUtils;
import cz.moneta.test.dsl.util.credentials.Keys;
import cz.moneta.test.harness.support.auth.AuthSupport;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.rest.RawRestRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class ElasticApiTasks {
    private final Harness harness;

    private static final Logger logger = LogManager.getLogger(ElasticApiTasks.class);

    public ElasticApiTasks(Harness harness) {
        this.harness = harness;
    }

    // Use with basic auth header "Authorization: Basic <generated token>")
    public String getAuthorizationToken() {
        Credentials cred = AuthSupport.getCredentials(Keys.elastic.sfindexuser, harness);
        return TestUtils.encodeBase64(cred.getUsername() + ":" + cred.getPassword());
    }

    public RawRestRequest.Response search(String index, String token, String jsonBody) {
        return harness.withElasticApi()
                .prepareReadRequest()
                .withPath(index + "/_search")
                .withHeader("Authorization", "Basic " + token)
                .withPayload(jsonBody)
                .post()
                .andAssertStatus(200);
    }

    public void bulk(String index, String token, String jsonBody) {
        harness.withElasticApi()
                .prepareReadRequest()
                .withPath(index + "/_bulk")
                .withHeader("Authorization", "Basic " + token)
                .withHeader("Content-Type", "application/json")
                .withPayload(jsonBody)
                .post()
                .andAssertStatus(200);
    }

    public LocalDateTime getBroadcomLastLogTime() {
        String result = harness.withElasticApi()
                .prepareReadRequest()
                .withPath("prod-fv-app*/_search")
                .withHeader("Authorization", "Basic " + AuthSupport.getAccessToken(Keys.elastic.broadcom, harness))
                .withPayload("{ " +
                    "\"size\" : 1, " +
                    "\"query\" : { " +
                        "\"match\" : { " +
                            "\"datasource_origin\" : \"db_broadcomm\"" +
                        "}" +
                    "}," +
                    "\"sort\": [ " +
                    "{" +
                        "\"@timestamp\" : {" +
                            "\"order\" : \"desc\"" +
                        "}" +
                    "}" +
                    "]," +
                    "\"fields\" : [" +
                        "\"@timestamp\"" +
                    "]," +
                    "\"_source\" : false" +
                    "}")
                .post()
                .andAssertStatus(200)
                .andAssertPresent("hits.hits[0].fields.@timestamp[0]")
                .extract("hits.hits[0].fields.@timestamp[0]")
                .asText();

       logger.info("Timestamp returned from elastic is: " + result);

       return LocalDateTime.parse(result, DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC));
    }

}
