using System.IO;
using System.Text;

namespace RevitToIfcConverter.Core.Tools
{
    public class StreamString
    {
        private readonly Stream _ioStream;
        private readonly UnicodeEncoding _streamEncoding;

        public StreamString(Stream ioStream)
        {
            _ioStream = ioStream;
            _streamEncoding = new UnicodeEncoding();
        }

        public string ReadString()
        {
            var length = _ioStream.ReadByte() * 256;
            length += _ioStream.ReadByte();
            var inBuffer = new byte[length];
            _ioStream.Read(inBuffer, 0, length);

            return _streamEncoding.GetString(inBuffer);
        }

        public int WriteString(string outString)
        {
            var outBuffer = _streamEncoding.GetBytes(outString);
            var length = outBuffer.Length;
            if (length > ushort.MaxValue)
            {
                length = ushort.MaxValue;
            }
            _ioStream.WriteByte((byte)(length / 256));
            _ioStream.WriteByte((byte)(length & 255));
            _ioStream.Write(outBuffer, 0, length);
            _ioStream.Flush();

            return outBuffer.Length + 2;
        }
    }
}
