package ex11;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;

public final class Profiler {
    private static final Map<CallInfo, LongAdder> count = new HashMap<>();

    private static final Path outFile = Path.of("ex11.csv");

    private static boolean stop = false;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            stop = true;
            try (final OutputStream path = Files.newOutputStream(outFile)) {
                final CallInfoCSVWriter w = new CallInfoCSVWriter(path);
                for (final var entry : count.entrySet()) {
                    System.out.println(entry.getKey().toString() + "\n#invokes " + entry.getValue().longValue() + "\n");
                    w.write(entry.getKey(), entry.getValue().longValue());
                }
                System.out.println("Invocations have been written to: " + outFile.toAbsolutePath());
            } catch (final IOException e) {
                throw new RuntimeException("Writing CSV file with call info failed", e);
            }
        }));
    }

    private Profiler() {
    }

    public static void registerCall(final CallInfo info) {
        if (stop) return;
        count.computeIfAbsent(info, ignored -> new LongAdder()).increment();
    }

}
