using System;
using System.Diagnostics;
using System.Linq;

using Patched.Dal;

namespace Patched.Bll
{
    public class ShellBo
    {
        public string Cmd { get; internal set; }

        public string StdOut { get; internal set; }

        public string StdError { get; internal set; }

        public int ExitCode { get; internal set; }

        public DateTime StartTime { get; internal set; }

        public DateTime ExitTime { get; internal set; }

        public DateTime Inserted { get; internal set; }

        public DateTime Updated { get; internal set; }

        public void PrintSummary()
        {
            Console.WriteLine($"ExitCode={ExitCode} at {ExitTime.ToString("yyyy-MM-ddTHH:mm:ss")}{(String.IsNullOrWhiteSpace(StdError) ? "" : ": Has StdErr")}: {Cmd}");
        }

        public void PrintDetails()
        {        
            if (String.IsNullOrEmpty(StdOut)) {
                Console.WriteLine("Stdout: Nothing Found");
            } else {
                Console.WriteLine("Stdout:");

                Console.WriteLine(StdOut);
            }                    

            if (String.IsNullOrEmpty(StdError)) {
                Console.WriteLine("StdError: Nothing Found");
            } else {
                Console.WriteLine("StdError:");

                Console.WriteLine(StdError);
            }                    

            Console.WriteLine($"ExitCode={ExitCode} at {ExitTime.ToString("yyyy-MM-ddTHH:mm:ss")}: {Cmd}");
        }
    }

    public class ShellBl
    {
        public static ShellBo Bash(string cmd)
        {
            var escapedArgs = cmd.Replace("\"", "\\\"");
            
            ProcessStartInfo StartInfo = new ProcessStartInfo {
                FileName = "/bin/bash",
                Arguments = $"-c \"{escapedArgs}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            ShellBo shellBo = new ShellBo {
                Cmd = cmd,
                StartTime = DateTime.Now
            };

            using (Process process = Process.Start(StartInfo))
            {
                process.WaitForExit();

                shellBo.StdOut = process.StandardOutput.ReadToEnd();            
                shellBo.StdError = process.StandardError.ReadToEnd();
                shellBo.ExitCode = process.ExitCode;
                shellBo.ExitTime = process.ExitTime;
            }

            // So we don't get a false positive
            shellBo.StdError = shellBo.StdError.Replace("nohup: ignoring input", "");

            AppDalShell.Insert(shellBo);

            return shellBo;
        }
    }
}