using NetPanel.Help;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetPanel.Bl
{
    public class ExecuteBl
    {


        public static string Exec(string fileName,string command)
        {
            

            if (OperatingSystem.IsWindows()) // 检查当前操作系统是否为 Windows
            {
                return ExecuteCommandOnWindows(fileName, command);
            }
            else if (OperatingSystem.IsLinux()) // 检查当前操作系统是否为 Linux
            {
                return ExecuteCommandOnLinux(fileName, command);
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// win 执行命令
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        private static string ExecuteCommandOnWindows(string fileName ,string command)
        {

            using var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = command,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    //StandardErrorEncoding = Encoding.UTF8,
                    //StandardOutputEncoding = Encoding.UTF8,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            process.Start();
            string output = process.StandardOutput.ReadToEnd();            
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();
            if (output.IsNull()) {
                return error;
            }
            return output;

        }

        /// <summary>
        /// linux 执行命令
        /// </summary>
        /// <param name="command"></param>
        private static string ExecuteCommandOnLinux(string fileName ,string command)
        {

            using var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = command,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    //StandardErrorEncoding = Encoding.UTF8,
                    //StandardOutputEncoding = Encoding.UTF8,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();
            if (output.IsNull())
            {
                return error;
            }
            return output;

        }

    }
}
