package p.studio.execution.runtime;

import p.studio.projects.ProjectReference;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;

public final class StudioExternalRuntimeProcessLauncher implements StudioRuntimeProcessLauncher {
    @Override
    public StudioRuntimeProcessHandle launch(
            final ProjectReference projectReference,
            final String runtimePath) throws IOException {
        final Process process = new ProcessBuilder(runtimePath, "debug", "build")
                .directory(projectReference.rootPath().toFile())
                .start();
        return new ExternalProcessHandle(process);
    }

    private record ExternalProcessHandle(Process process) implements StudioRuntimeProcessHandle {
        @Override
        public InputStream stdout() {
            return process.getInputStream();
        }

        @Override
        public InputStream stderr() {
            return process.getErrorStream();
        }

        @Override
        public boolean isAlive() {
            return process.isAlive();
        }

        @Override
        public void destroyForcibly() {
            process.descendants().forEach(ProcessHandle::destroyForcibly);
            process.destroyForcibly();
        }

        @Override
        public CompletableFuture<Integer> onExit() {
            return process.onExit().thenApply(Process::exitValue);
        }
    }
}
