using System.Text;
using DataModel;
using Microsoft.Data.Sqlite;

namespace Processor;

public static class ExtensionsError
{
    public static ProcessorResult<TResult> ToProcessorResult<TResult>(this Exception exception) where TResult : class
    {
        if(exception.InnerException is SqliteException sqliteException)
            if (sqliteException.SqliteErrorCode is 14)
            {
                var blockingProcesses = SystemUtil.WhoIsLocking(Setup.DataFile);
                var sb = new StringBuilder();
                sb.AppendLine($"The data file is used by the {blockingProcesses.Count} other process(es) listed below:");
                foreach (var blockingProcess in blockingProcesses)
                    sb.AppendLine($"- {blockingProcess.ProcessName} (id={blockingProcess.Id})");
                
                // Is there only one process and it is this one?
                if (blockingProcesses.Count == 1 && blockingProcesses.First().ProcessName == "I18N Commander")
                {
                    sb.AppendLine();
                    sb.AppendLine("Hint: Is the ransomware protection enabled in your Windows system? If so, please make sure that the I18N Commander has write permission.");
                }
                
                return new ProcessorResult<TResult>(null, false, sb.ToString());
            }
            else
                return new ProcessorResult<TResult>(null, false, $"A database error occurred: '{sqliteException.Message}'");
            
        return new ProcessorResult<TResult>(null, false, $"A database error occurred: '{exception.Message}'");
    }
}