using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Threading;

namespace XHWK.WKTool.Helpers
{
    internal class ZJDownloadUtil
    {
        public static void downloadFile(string url, string savepath)
        {
            string path = savepath;
            string filename = url.Substring(url.LastIndexOf("/") + 1);
            if (!url.StartsWith("http") || filename == null || filename == "")
            {
                return;
            }
            path += filename;
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);

            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }

        /// <summary>
        /// Http下载文件
        /// </summary>
        public static Thread downloadFileWithCallback(
            string url,
            int position,
            string savepath,
            Dispatcher dispatcher,
            ZJDownloadCallback callback
            )
        {

            string path = savepath;
            string filename = url.Substring(url.LastIndexOf("/") + 1);
            path += filename;
            if (!url.StartsWith("http") || filename == null || filename == "")
            {
                return null;
            }
            Thread thread = new Thread(o =>
            {
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    dispatcher.Invoke(new Action(() =>
                    {
                        callback.downloadEnd(position, path);
                    }));
                }
                else
                {
                    string temppath = path + ".tmp";
                    if (File.Exists(temppath))
                    {
                        //File.Delete(temppath);
                        temppath += "1";
                        while (File.Exists(temppath))
                        {
                            temppath += "1";
                            if (!File.Exists(temppath))
                            {
                                break;
                            }
                        }

                    }

                    dispatcher.Invoke(new Action(() =>
                    {
                        callback.downloadBegin(position);
                    }));

                    try
                    {
                        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        Stream responseStream = response.GetResponseStream();

                        //创建本地文件写入流
                        Stream stream = new FileStream(temppath, FileMode.Create);
                        long totalSize = response.ContentLength;
                        byte[] bArr = new byte[1024];
                        int size = responseStream.Read(bArr, 0, bArr.Length);
                        long readsize = 0;
                        while (size > 0)
                        {
                            readsize += size;
                            stream.Write(bArr, 0, size);
                            size = responseStream.Read(bArr, 0, bArr.Length);

                            dispatcher.Invoke(new Action(() =>
                            {
                                callback.downloadProgress(position, (int)(readsize * 100 / totalSize));
                            }));
                        }
                        stream.Close();
                        responseStream.Close();
                        FileInfo fitemp = new FileInfo(temppath);
                        fitemp.MoveTo(path);
                        dispatcher.Invoke(new Action(() =>
                        {
                            callback.downloadEnd(position, path);
                        }));
                    }
                    catch (Exception ex)
                    {
                        dispatcher.Invoke(new Action(() =>
                        {
                            callback.downloadError(position, ex.Message);
                        }));

                    }

                }
            });
            thread.Start();
            return thread;
        }




        public static void downloadFileWithCallback(
            string url,
            int position,
            Dispatcher dispatcher,
            ZJDownloadCallback callback
            )
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "temp\\";
            downloadFileWithCallback(url, position, path, dispatcher, callback);
        }

        public interface ZJDownloadCallback
        {
            /// <summary>
            /// 下载开始
            /// </summary>
            /// <param name="position"></param>
            void downloadBegin(int position);

            /// <summary>
            /// 下载过程
            /// </summary>
            /// <param name="position"></param>
            /// <param name="progress"></param>
            void downloadProgress(int position, int progress);

            /// <summary>
            /// 下载结束
            /// </summary>
            /// <param name="position"></param>
            /// <param name="filepath"></param>
            void downloadEnd(int position, string filepath);
            /// <summary>
            /// 下载结束
            /// </summary>
            /// <param name="position"></param>
            /// <param name="filepath"></param>
            void downloadError(int position, string msg);

        }
    }
}
