﻿using System;
using System.IO;
using Buftaku_Subtitle_Utility.Serialization;
using System.Threading.Tasks;

namespace Buftaku_Subtitle_Utility.Subtitle.Parser
{
    public class BinParser : ISubtitlesParser
    {
        public async Task<SubtitleData> ParseStream(Stream binStream, System.Text.Encoding encoding)
        {
            var subtitleData = new SubtitleData();

            await Task.Run(() =>
            {
                // test if stream if readable and seekable (just a check, should be good)
                if (!binStream.CanRead || !binStream.CanSeek)
                {
                    throw new ArgumentException(nameof(binStream));
                }

                // seek the beginning of the stream
                binStream.Position = 0;

                byte[] data;

                var buffer = new byte[16 * 1024];
                using (var ms = new MemoryStream())
                {
                    int read;
                    while ((read = binStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    data = ms.ToArray();
                }

                var deserializedData = data.DeserializeAs<SubtitleData>();
                deserializedData.Format = SubtitleFormat.Binary;

                subtitleData = deserializedData;
            });

            return subtitleData;
        }
    }
}