using System;
using SabreTools.Core.Filter;
using SabreTools.Models.Metadata;
using SabreTools.Serialization.Interfaces;
namespace SabreTools.DatFiles.Formats
{
///
/// Represents a DAT that can be serialized
///
/// Base internal model for the DAT type
/// IFileDeserializer type to use for conversion
/// IFileSerializer type to use for conversion
/// IModelSerializer for cross-model serialization
public abstract class SerializableDatFile : DatFile
where TFileDeserializer : IFileDeserializer
where TFileSerializer : IFileSerializer
where TModelSerializer : IModelSerializer
{
///
protected SerializableDatFile(DatFile? datFile) : base(datFile) { }
///
public override void ParseFile(string filename,
int indexId,
bool keep,
bool statsOnly = false,
FilterRunner? filterRunner = null,
bool throwOnError = false)
{
try
{
// Deserialize the input file in two steps
var specificFormat = Activator.CreateInstance().Deserialize(filename);
var internalFormat = Activator.CreateInstance().Serialize(specificFormat);
// Convert to the internal format
ConvertFromMetadata(internalFormat, filename, indexId, keep, statsOnly, filterRunner);
}
catch (Exception ex) when (!throwOnError)
{
string message = $"'{filename}' - An error occurred during parsing";
_logger.Error(ex, message);
}
}
///
public override bool WriteToFile(string outfile, bool ignoreblanks = false, bool throwOnError = false)
{
try
{
_logger.User($"Writing to '{outfile}'...");
// Serialize the input file in two steps
var internalFormat = ConvertToMetadata(ignoreblanks);
var specificFormat = Activator.CreateInstance().Deserialize(internalFormat);
if (!Activator.CreateInstance().Serialize(specificFormat, outfile))
{
_logger.Warning($"File '{outfile}' could not be written! See the log for more details.");
return false;
}
}
catch (Exception ex) when (!throwOnError)
{
_logger.Error(ex);
return false;
}
_logger.User($"'{outfile}' written!{Environment.NewLine}");
return true;
}
///
public override bool WriteToFileDB(string outfile, bool ignoreblanks = false, bool throwOnError = false)
{
try
{
_logger.User($"Writing to '{outfile}'...");
// Serialize the input file in two steps
var internalFormat = ConvertToMetadataDB(ignoreblanks);
var specificFormat = Activator.CreateInstance().Deserialize(internalFormat);
if (!Activator.CreateInstance().Serialize(specificFormat, outfile))
{
_logger.Warning($"File '{outfile}' could not be written! See the log for more details.");
return false;
}
}
catch (Exception ex) when (!throwOnError)
{
_logger.Error(ex);
return false;
}
_logger.User($"'{outfile}' written!{Environment.NewLine}");
return true;
}
}
}