package org.raddatz.familienarchiv.ocr;

import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;

import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static org.assertj.core.api.Assertions.assertThat;

class RestClientOcrClientTrainingTest {

    @Test
    void trainSenderModel_postsToTrainSenderEndpoint() throws Exception {
        List<String> capturedPaths = new CopyOnWriteArrayList<>();
        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
        server.createContext("/", exchange -> {
            capturedPaths.add(exchange.getRequestURI().getPath());
            byte[] response = "{\"loss\":0.1,\"accuracy\":0.95,\"cer\":0.05,\"epochs\":3}"
                    .getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            exchange.sendResponseHeaders(200, response.length);
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response);
            }
        });
        server.start();

        try {
            int port = server.getAddress().getPort();
            RestClientOcrClient client = new RestClientOcrClient("http://localhost:" + port, "");
            client.trainSenderModel(new byte[]{1, 2, 3}, "/app/models/sender_test.mlmodel");
            assertThat(capturedPaths).contains("/train-sender");
        } finally {
            server.stop(0);
        }
    }
}
