using System.Collections.Generic;
using System.IO;
using System.Text;
using SabreTools.Data.Models.EverdriveSMDB;
using SabreTools.IO.Extensions;
using SabreTools.Text.SeparatedValue;

namespace SabreTools.Serialization.Writers
{
    public class EverdriveSMDB : BaseBinaryWriter<MetadataFile>
    {
        /// <inheritdoc/>
        public override Stream? SerializeStream(MetadataFile? obj)
        {
            // If the metadata file is null
            if (obj is null)
                return null;

            // Setup the writer and output
            var stream = new MemoryStream();
            var writer = new Writer(stream, Encoding.UTF8) { Separator = '\t', Quotes = false };

            // Write out the rows, if they exist
            WriteRows(obj.Row, writer);

            // Return the stream
            stream.SeekIfPossible(0, SeekOrigin.Begin);
            return stream;
        }

        /// <summary>
        /// Write rows information to the current writer
        /// </summary>
        /// <param name="rows">Array of Row objects representing the rows information</param>
        /// <param name="writer">Writer representing the output</param>
        private static void WriteRows(Row[]? rows, Writer writer)
        {
            // If the games information is missing, we can't do anything
            if (rows is null || rows.Length == 0)
                return;

            // Loop through and write out the rows
            foreach (var row in rows)
            {
                if (row is null)
                    continue;

                var rowArray = new List<string?>
                {
                    row.SHA256,
                    row.Name,
                    row.SHA1,
                    row.MD5,
                    row.CRC32,
                };

                if (row.Size is not null)
                    rowArray.Add(row.Size?.ToString());

                writer.WriteValues([.. rowArray]);
                writer.Flush();
            }
        }
    }
}
