using Newtonsoft.Json;
using System.Diagnostics;
using System;
using System.Text.RegularExpressions;
using Serilog;
using Serilog.Core;

namespace Runas
{
    class Program
    {
        public static string DataText = RegexAllEnv(Runas.Properties.Resources.progs);
        public static dynamic jprograms = JsonConvert.DeserializeObject(DataText);
        public static string RegexAllEnv(string data)
        {
            System.Collections.Hashtable env = (System.Collections.Hashtable)Environment.GetEnvironmentVariables();
            string val;
            foreach (System.Collections.DictionaryEntry key in env)
            {
                val = (string)key.Value;
                val = val.Replace(@"\", @"\\");
                if (key.Key is not (object)"Path" and not (object)"path")
                {
                    data = val.EndsWith(@"\") ? Regex.Replace(data, $"\\u0025{key.Key}\\u0025\\\\", val, RegexOptions.IgnoreCase) : Regex.Replace(data, $"\\u0025{key.Key}\\u0025", val, RegexOptions.IgnoreCase);
                    // val.EndsWith(@"\")? data.Replace($"%{key.Key}%\\", val) : data.Replace($"%{key.Key}%",val);
                }
            }
            return data;
        }
        public static bool DoRun(string program)
        {
            Process[] process = Process.GetProcessesByName(program);
            Log.Information($"{program}:{process.Length > 0}");
            return (process.Length > 0);
        }
        public static void RunProcess(string programName)
        {

            if (!(DoRun(programName)))
            {
                if (programName.Equals("AutoHotKey"))
                {
                    Log.Information($"\u0022{jprograms[programName][1].Value.ToString()}\u0022");
                    ProcessStartInfo proc = new();
                    proc.UseShellExecute= false;
                    proc.Arguments = $"\u0022{jprograms[programName][1].Value.ToString()}\u0022";
                    proc.FileName = jprograms[programName][0].Value;
                    proc.RedirectStandardError = true;
                    Log.Information(Process.Start(proc).StandardError.ReadToEnd());
                    //Process.Start(jprograms[programName][0].Value, $"\u0022{jprograms[programName][1].Value.ToString()}\u0022");
                }

                else if (jprograms[programName].Count > 1)
                {
                    foreach (var prog in jprograms[programName])
                    {
                        if (System.IO.File.Exists(prog.Value))
                        {
                            Log.Information($"{prog.Value}");
                            Process.Start(prog.Value);
                        }
                    }
                }
                else if (jprograms[programName].Count == 1)
                {
                    if (System.IO.File.Exists(jprograms[programName][0].Value))
                    {
                        Log.Information($"{jprograms[programName][0].Value}");
                    Process.Start(jprograms[programName][0].Value);
                    }
                }
            }
        }
        static void Main(string[] args)
        {
          Log.Logger =  new LoggerConfiguration().WriteTo.File(
                 $"{Environment.CurrentDirectory}/Logs/{DateTime.Now:yyyy-MM-dd}.log",
                 Serilog.Events.LogEventLevel.Information,
                  "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}[{Level: u3}] {Message:lj}{NewLine}",
                  rollingInterval: RollingInterval.Hour)
                  .CreateLogger();
            foreach (var prog in jprograms)
            {
                string ProgProg = ((Newtonsoft.Json.Linq.JProperty)prog).Name;
                System.Threading.Thread thread = new(new System.Threading.ThreadStart(() => RunProcess(ProgProg)));
                thread.Start();
            }
        }
    }
}
