using System.Diagnostics;
using System;
using Serilog;
using LiteDB;

namespace Runas
{
    class Program
    {
      
        public static bool DoRun(string program)
        {
            Process[] process = Process.GetProcessesByName(program);
            Log.Information($"{program}:{process.Length > 0}");
            return (process.Length > 0);
        }
      
        static void RunMe(Prog prog, bool verb = false)
        {
            if (!DoRun(prog._id))
            {
                Log.Information(prog._id);
                ProcessStartInfo proc = new();
                proc.UseShellExecute= true;
                if(prog.Arguments is not null) { 
                    proc.Arguments= prog.Arguments;
                }
                proc.FileName = prog.File;
               if (verb)
                {
                    proc.Verb = "runas";
                }
                if (System.IO.File.Exists(proc.FileName))
                {

                    Process.Start(proc);
                    Log.Information(proc.FileName);
                }
            }
        }
        static void Main(string[] args)
        {
            var data = new LiteDatabase(@"Resources/fu");
            
          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 item in data.GetCollection<Prog>("justrun").FindAll()) { 
                RunMe(item);
            }
            foreach (var item in data.GetCollection<Prog>("runas").FindAll())
            {
                RunMe(item, true);
            }
            return;
        }
    }
}
