using System.Xml.Serialization;

namespace Harmonia.Core.Data;

public abstract class XMLFileRepository<TObject> : FileRepository<TObject> where TObject : notnull, new()
{
    private readonly XmlSerializer _serializer = new(typeof(TObject));

    protected override string Extension => "xml";

    protected override TObject Deserialize(Stream stream)
    {
        using TextReader textReader = new StreamReader(stream);

        return (TObject?)_serializer.Deserialize(textReader) ?? new();
    }

    protected override string Serialize(TObject obj)
    {
        using TextWriter textWriter = new StringWriter();

        _serializer.Serialize(textWriter, obj);

        return textWriter.ToString() ?? string.Empty;
    }
}