using Common.Model;

using System;
using System.IO;
using System.Net;

namespace Common.system
{
    /// <summary>
    /// 下载方法
    /// 创建人：赵耀
    /// 创建时间：2018年10月30日
    /// </summary>
    public class DownloadService
    {
        private string _downloadUrl = ""; //文件下载地址
        private string _filePath = ""; //文件保存路径
        private string _method = ""; //方法
        private long _fromIndex; //开始下载的位置
        private long _toIndex; //结束下载的位置
        private long _count; //总大小
        private readonly long _size = 524288; //每次下载大小 512kb
        private bool _isRun; //是否正在进行

        public bool isFinish; //是否已下载完成{ get; private set; }

        public bool isStopped = true;//是否已停止{ get; private set; }

        /// <summary>
        /// 开始下载
        /// </summary>
        public event Action OnStart;
        /// <summary>
        /// 下载进度
        /// </summary>
        public event Action OnDownload;
        /// <summary>
        /// 完成下载
        /// </summary>
        public event Action OnFinsh;
        /// <summary>
        /// 断开网络连接
        /// </summary>
        public event Action OnDisconnect;


        public long GetDownloadedCount()
        {
            return _count - _toIndex + _fromIndex - 1;
        }

        public void Stop()
        {
            _isRun = false;
        }

        /// <summary>
        /// 开始下载
        /// </summary>
        /// <param name="info"></param>
        /// <param name="isReStart"></param>
        /// <returns></returns>
        public bool Start(TaskInfoModel info, bool isReStart)
        {
            _downloadUrl = info.downloadUrl;
            _fromIndex = info.fromIndex;
            _toIndex = info.toIndex;
            _method = info.method;
            _filePath = info.filePath;
            _count = info.count;
            isStopped = false;
            if (File.Exists(_filePath))
            {
                if (isReStart)
                {
                    File.Delete(_filePath);
                    File.Create(_filePath).Close();
                }
            }
            else
            {
                File.Create(_filePath).Close();
            }
            using (FileStream file = File.Open(_filePath, FileMode.Open))
            {
                _fromIndex = info.fromIndex + file.Length;
            }
            if (_fromIndex >= _toIndex)
            {
                OnFineshHandler();
                isFinish = true;
                isStopped = true;
                return false;
            }
            OnStartHandler();
            _isRun = true;
            new Action(() =>
            {
                while (_fromIndex < _toIndex && _isRun)
                {
                    long to;
                    if (_fromIndex + _size >= _toIndex - 1)
                    {
                        to = _toIndex - 1;
                    }
                    else
                    {
                        to = _fromIndex + _size;
                    }
                    try
                    {
                        WebResponse rsp;
                        using (rsp = ZHttpUtil.Download(
                                   _downloadUrl,
                                   _fromIndex,
                                   to,
                                   _method
                               ))
                        {
                            Save(_filePath, rsp.GetResponseStream());
                        }
                    }
                    catch (Exception ex)
                    {
                        string errMessage = "【下载】(DownloadService):" + ex.Message;
                        LogHelper.Logerror.Error(errMessage, ex);
                        OnDisconnectHandler();
                        return;
                    }
                }
                if (!_isRun)
                {
                    isStopped = true;
                }
                if (_fromIndex >= _toIndex)
                {
                    isFinish = true;
                    isStopped = true;
                    OnFineshHandler();
                }

            }).BeginInvoke(null, null);
            return true;
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="stream"></param>
        private void Save(string filePath, Stream stream)
        {
            try
            {
                using (FileStream writer = File.Open(filePath, FileMode.Append))
                {
                    using (stream)
                    {
                        int repeatTimes = 0;
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = stream.Read(buffer, 0, buffer.Length)) > 0 && _isRun)
                        {
                            writer.Write(buffer, 0, length);
                            _fromIndex += length;
                            if (repeatTimes % 5 == 0)
                            {
                                OnDownloadHandler();
                            }
                            repeatTimes++;
                        }
                    }
                }
                OnDownloadHandler();
            }
            catch (Exception)
            {
                //异常也不影响
            }
        }
        /// <summary>
        /// 开始下载
        /// </summary>
        private void OnStartHandler()
        {
            new Action(() =>
            {
                if (OnStart != null)
                {
                    OnStart.Invoke();
                }
            }).BeginInvoke(null, null);
        }
        /// <summary>
        /// 完成下载
        /// </summary>
        private void OnFineshHandler()
        {
            new Action(() =>
            {
                if (OnFinsh != null)
                {
                    OnFinsh.Invoke();
                }

                if (OnDownload != null)
                {
                    OnDownload.Invoke();
                }
            }).BeginInvoke(null, null);
        }
        /// <summary>
        /// 下载进度
        /// </summary>
        private void OnDownloadHandler()
        {
            new Action(() =>
            {
                if (OnDownload != null)
                {
                    OnDownload.Invoke();
                }
            }).BeginInvoke(null, null);
        }
        /// <summary>
        /// 断开网络连接
        /// </summary>
        private void OnDisconnectHandler()
        {
            new Action(() =>
            {
                if (OnDisconnect != null)
                {
                    OnDisconnect.Invoke();
                }
            }).BeginInvoke(null, null);

        }
    }
}
