﻿using DNCP.Util;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace DNCP.AngleSharpDemo.Service
{
    /// <summary>
    /// 文件下载服务
    /// </summary>
    public class FileDownloadService
    {
        /// <summary>
        /// 远程文件下载
        /// </summary>
        /// <param name="remoteUrl"></param>
        /// <param name="savePath"></param>
        public static async Task RemoteFileDownload(string remoteUrl, string savePath)
        {
            if (string.IsNullOrWhiteSpace(remoteUrl) || string.IsNullOrWhiteSpace(savePath)) return;
            try
            {
                using (HttpResponseMessage response = HttpClientUtilAsync.GetHttpClient().GetAsync(remoteUrl, HttpCompletionOption.ResponseHeadersRead).Result)
                {
                    response.EnsureSuccessStatusCode();

                    var fileName = Path.GetFileName(savePath);
                    var directory = Path.GetDirectoryName(savePath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    var totalSize = response.Content.Headers.ContentLength;
                    using (Stream contentStream = await response.Content.ReadAsStreamAsync(), fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        var totalRead = 0L;
                        var totalReads = 0L;
                        var buffer = new byte[8192];
                        var isMoreToRead = true;

                        do
                        {
                            var read = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                            if (read == 0)
                            {
                                Console.WriteLine($"{fileName}:下载完成.");
                                isMoreToRead = false;
                            }
                            else
                            {
                                await fileStream.WriteAsync(buffer, 0, read);

                                totalRead += read;
                                totalReads += 1;

                                if (totalReads % 1024 == 0)
                                {
                                    var process = totalRead / (double)totalSize * 100;
                                    Console.WriteLine($"{fileName}:已下载大小 {Math.Round((totalRead / (double)1024) / 1024, 2)}M 进度: {Math.Round(process, 2)}% ");
                                }
                            }
                        }
                        while (isMoreToRead);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
