import org.jobrunr.configuration.JobRunr;
import org.jobrunr.scheduling.BackgroundJob;
import org.jobrunr.server.BackgroundJobServerConfiguration;
import org.jobrunr.storage.InMemoryStorageProvider;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/** Starts the built-in dashboard on port 8000 and asks it for its own view of the jobs over HTTP. */
public class DashboardDemo {

    public static class Task {
        public void run(int n) { System.out.println("  task " + n); }
    }

    public static void main(String[] args) throws Exception {
        JobRunr.configure()
                .useStorageProvider(new InMemoryStorageProvider())
                .useBackgroundJobServer(BackgroundJobServerConfiguration.usingStandardBackgroundJobServerConfiguration()
                        .andPollInterval(Duration.ofSeconds(5)))
                .useDashboard(8000)
                .initialize();
        var t = new Task();
        for (int i = 1; i <= 3; i++) {
            int n = i;
            BackgroundJob.enqueue(() -> t.run(n));
        }
        Thread.sleep(9_000);
        var http = HttpClient.newHttpClient();
        for (String path : new String[] {"/", "/api/jobs?state=SUCCEEDED", "/api/servers", "/api/problems"}) {
            var res = http.send(HttpRequest.newBuilder(URI.create("http://localhost:8000" + path)).build(),
                    HttpResponse.BodyHandlers.ofString());
            String body = res.body().replaceAll("\\s+", " ");
            System.out.println("GET " + path + " -> " + res.statusCode() + " " + res.headers().firstValue("content-type").orElse("")
                    + " " + body.substring(0, Math.min(150, body.length())));
        }
        JobRunr.destroy();
    }
}
