using System;
using SabreTools.Models.Metadata;
using SabreTools.Serialization.Interfaces;
namespace SabreTools.DatFiles
{
///
/// 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, 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
ConvertMetadata(internalFormat, filename, indexId, keep, statsOnly);
}
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 = ConvertMetadata(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 = ConvertMetadataDB(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;
}
}
}