using Microsoft.Extensions.Options;
using PrintService.Models;
using System.Drawing;
using System.Drawing.Printing;
using System.Text.RegularExpressions;
namespace PrintService.Services;
///
/// Processes documents and renders them for printing
///
public class DocumentProcessor
{
private readonly AppSettings _settings;
private readonly ILogger _logger;
public DocumentProcessor(IOptions settings, ILogger logger)
{
_settings = settings.Value;
_logger = logger;
}
///
/// Process and transform document content
///
public string ProcessDocument(string content, DocumentConfig config)
{
var processed = content;
// Apply text transformations
foreach (var transform in config.Transformations)
{
try
{
processed = Regex.Replace(processed, transform.Pattern, transform.Replacement);
if (_settings.VerboseLogging)
{
_logger.LogDebug("Applied transformation: {Description}", transform.Description);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to apply transformation: {Pattern}", transform.Pattern);
}
}
return processed;
}
///
/// Get document configuration by type
///
public DocumentConfig? GetDocumentConfig(string documentType)
{
return _settings.DocumentTypes.FirstOrDefault(dt =>
dt.Name.Equals(documentType, StringComparison.OrdinalIgnoreCase));
}
///
/// Read file content
///
public string ReadFile(string filePath)
{
return File.ReadAllText(filePath);
}
///
/// Archive or delete file after processing
///
public void PostProcess(PrintJob job, DocumentConfig config)
{
try
{
// Skip post-processing if configured (useful for testing)
if (config.SkipPostProcessing)
{
_logger.LogInformation("Skipping post-processing for job {JobId} (file remains in queue)", job.Id);
return;
}
if (config.ArchiveAfterPrint && !string.IsNullOrEmpty(config.ArchivePath))
{
Directory.CreateDirectory(config.ArchivePath);
var archiveFileName = Path.Combine(config.ArchivePath,
$"{DateTime.Now:yyyyMMdd_HHmmss}_{job.OriginalFilename}");
if (File.Exists(job.QueuedFilePath))
{
File.Move(job.QueuedFilePath, archiveFileName);
_logger.LogInformation("Archived job {JobId} to {Path}", job.Id, archiveFileName);
}
}
else
{
if (File.Exists(job.QueuedFilePath))
{
File.Delete(job.QueuedFilePath);
_logger.LogInformation("Deleted file for job {JobId}", job.Id);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to post-process job {JobId}", job.Id);
}
}
}