using System.Diagnostics;
using System.Text;

namespace File_Folder_Helper.Helpers;

internal static class HelperILMerge
{

    internal static void ILMerge(string workingDirectory)
    {
        bool result;
        ProcessStartInfo processStartInfo;
        StringBuilder stringBuilder = new();
        string[] successChecks = ["success"];
        string[] errorChecks = ["Error", "Conflict", "error:"];
        FileInfo ilMerge = new("C:/Users/phares/AppData/Local/IFXApps/ILMerge/ILMerge.exe");
        string[] dllFiles = Directory.GetFiles(workingDirectory, "*.dll", SearchOption.TopDirectoryOnly);
        string errorFile = Path.Combine(workingDirectory, string.Concat(Path.GetFileName(workingDirectory), ".err"));
        string primaryFile = Path.Combine(workingDirectory, string.Concat(Path.GetFileName(workingDirectory), ".dll"));
        FileInfo fileInfo = new(Path.Combine(workingDirectory, ilMerge.Name));
        if (!fileInfo.Exists)
            _ = ilMerge.CopyTo(fileInfo.FullName);
        if (fileInfo.Exists && ilMerge.LastWriteTime != fileInfo.LastWriteTime)
            _ = ilMerge.CopyTo(fileInfo.FullName, overwrite: true);
        _ = stringBuilder.Append("/allowDup /target:library /out:\"").Append(Path.GetFileNameWithoutExtension(primaryFile)).Append(".all.dll\" ");
        foreach (string dllFile in dllFiles)
        {
            if (dllFile == primaryFile)
                continue;
            _ = stringBuilder.Append('"').Append(Path.GetFileName(dllFile)).Append("\" ");
        }
        processStartInfo = new ProcessStartInfo(fileInfo.FullName, stringBuilder.ToString())
        {
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            WorkingDirectory = workingDirectory,
        };
        result = HelperStart.Start(errorChecks, successChecks, processStartInfo, errorFile);
        if (result)
        { }
    }

}