package org.minager.core.services.business;

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

import org.minager.core.entities.business.SystemResult;
import org.springframework.stereotype.Service;

@Service
public class SystemService {
	
	public SystemResult executeCommand(final String pCommand, final String... pArgs) {
		final String command = buildCommand(pCommand, pArgs);
		
		final SystemResult commandResults = new SystemResult();
        
        try {
            // Process creation and execution of the command.
            final Process process = Runtime.getRuntime().exec(command);
            
            // Waiting the end of the command execution.
            process.waitFor();
            
            // Getting of the stantard command output, and the standard error output.
            BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            
            String tempLine = null;
            while((tempLine = outputReader.readLine()) != null) {
                commandResults.addOutputLine(tempLine);
            }
            
            while((tempLine = errorReader.readLine()) != null) {
                commandResults.addErrorLine(tempLine);
            }
            
            commandResults.setResultCode(process.exitValue());
        } catch(IOException | InterruptedException ex) {
//            LOGGER.error(StringUtils.concat("Une erreur est survenue lors de l'exécution de la commande \"", command,
//                    "\"."), ex);
        	System.err.println(ex.getMessage());
        	ex.printStackTrace();
        }
        
        return commandResults;
	}
	
	/**
     * Build the command in form of one string from the parameters.
     * 
     * @param pCommand
     *            The command to execute.
     * @param pArgs
     *            The command arguments, could be {@code null}.
     * @return The command built.
     */
    private String buildCommand(final String pCommand, final Object... pArgs) {
        final StringBuilder command = new StringBuilder(pCommand);
 
        if (pArgs != null) {
            for (final Object arg : pArgs) {
                command.append(" ").append(arg);
            }
        }
 
        return command.toString();
    }
}
