package com.realnet.OpenAi.Services;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public class ScriptRunnerService {

	public ResponseEntity<?> runScript(String filepath, String filename) throws IOException {

		System.out.println("runScript method called in ScriptRunnerController");

		String str = null;

		String path = filepath + "/" + filename;

		ProcessBuilder pb = new

		ProcessBuilder(path);

		System.out.println("file taken =" + new File(path).getAbsoluteFile());

		pb.directory(new File(System.getProperty("user.home")));

		Process process = pb.start();
		if (process.isAlive()) {

			BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getInputStream()));

			System.out.println("file is running");

			while ((str = br2.readLine()) != null) {
				System.out.println(str);
			}
			br2.close();
			return new ResponseEntity<>(HttpStatus.OK);
		} else {
			return new ResponseEntity<>("bad request", HttpStatus.BAD_REQUEST);
		}

	}

}
