using Seenginx.Models;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Seenginx.Services
{
	public class CommandService
	{
		public async Task<Result<string>> RunCommandAsync(string command)
		{
			var runResult = new Result<string>();
			try
			{
				var output = string.Empty;

				var cmd = new ProcessStartInfo("CMD.exe", $"/C {command}");
				cmd.UseShellExecute = false;
				cmd.RedirectStandardInput = true;
				cmd.RedirectStandardOutput = true;
				cmd.CreateNoWindow = true;
				if (Environment.OSVersion.Platform.ToString().StartsWith("Win"))
					cmd.WorkingDirectory = @"C:\Program Files\nginx";

				using (var process = Process.Start(cmd))
				using (var reader = process.StandardOutput)
						output = reader.ReadToEnd();
				
				runResult.SetData(output);
				return runResult;
			}
			catch (Exception ex)
			{
				return runResult.Invalidate($"Error at running the command '{command}'", ex);
			}
		}
	}
}
