using System;
using System.IO;
using System.Threading;
using LJLib.Jdt;

namespace LJLib.Tools.Helper
{
    public class StreamHelper
    {
        public static void StreamCopy(Stream dest, Stream source, int len, IJdt jdt = null)
        {
            byte[] buff = new byte[10240];
            int total = 0;
            while (total < len)
            {
                var read = source.Read(buff, 0, Math.Min(buff.Length, len - total));
                if (read > 0)
                {
                    dest.Write(buff, 0, read);
                    dest.Flush();
                    total += read;
                    if (jdt != null)
                    {
                        jdt.Inc(total);
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }

        public static void StreamCopy(Stream dest, Stream source, IJdt jdt = null)
        {
            byte[] buff = new byte[10240];
            int read = 0;
            int total = 0;
            while ((read = source.Read(buff, 0, buff.Length)) > 0)
            {
                dest.Write(buff, 0, read);
                dest.Flush();
                total += read;
                if (jdt != null)
                {
                    jdt.Inc(total);
                }
            }
        }

    }
}
