using CCWin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace MOKA_Factory_Tools
{
    public partial class Upgrade : Skin_Color
    {
        public string RequireHost;//请求的服务器地址
        public string DownloadLink;//key包的下载地址
        public string DownloadSize;//key包的大小
        public string Ordername;//订单号
        public string Ordernumber;//订单数量
        public string Orderclient;//客户机型
        public string OrderPID;//PID
        public string OrderSV;//软件版本
        public string packet_md5;//key包的MD5校验
        public bool[] threadendTag;//判断各线程是否接收完文件
        public string[] filenameList;//各线程下载的小文件名列表
        public int[] filestartpos;//各线程开始读取文件的位置
        public int[] filesize;//小文件大小
        public string url;//请求链接
        public bool union;//判断文件是否合并完成
        public int thread;//线程数
        public bool EEPROMNow;//合成EEPROMkey
        public SQLiteConnection errorDBNow;
        public int wholesize;
        public string factorynumNow;
        public Upgrade(System.Data.SQLite.SQLiteConnection errorDB, string DownloadLinkInput, string factorynum)
        {
            InitializeComponent();
            skinLabel1.Text = LResource.DownloadUpgradePackage;
            this.Text = LResource.Download;
            Control.CheckForIllegalCrossThreadCalls = false;
            DownloadLink = DownloadLinkInput;//
            errorDBNow = errorDB;
            factorynumNow = factorynum;
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        public void StartDownload()
        {
            url = DownloadLink;
            HttpWebRequest request;
            long filesizew = 0;
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(url);//建立一个HTTP请求
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                filesizew = response.ContentLength;//得到文件总大小
                response.Close();
                request.Abort();//取消请求
            }
            catch (Exception ex)
            {
                MessageBox.Show(LResource.Error + ": " + ex.Message, LResource.Error);        
                Log.WriteErrorLog("\r\nCreate Http require error:"+ ex.Message);
                CommonMethod.ReportErrormsg("Fail to init download process", ex.Message + "\r\ndownload link:" + url, errorDBNow);
                return;
            }

            thread = Convert.ToInt32("1", 10);
            threadendTag = new bool[thread];
            filenameList = new string[thread];
            filestartpos = new int[thread];
            filesize = new int[thread];

            int filethread = (int)filesizew / thread;
            int filethreade = filethread + (int)filesizew % thread;
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\";

            //文件大小切割
            for (int i = 0; i < thread; i++)
            {
                threadendTag[i] = false;
                filenameList[i] = filePath + Path.GetFileName(DownloadLink); ;//+ "-" + i.ToString()
                if (i < thread - 1)
                {
                    filestartpos[i] = filethread * i;
                    filesize[i] = filethread - 1;
                }
                else
                {
                    filestartpos[i] = filethread * i;
                    filesize[i] = filethreade - 1;
                }
            }

           Thread[] threadk = new Thread[thread];
           HttpFile2[] httpfile = new HttpFile2[thread];

            //各进程开始下载
            for (int j = 0; j < thread; j++)
            {
                httpfile[j] = new HttpFile2(this, j);
                threadk[j] = new Thread(new ThreadStart(httpfile[j].ReceiveFile));
                threadk[j].Start();
            }
        }

        private void Download_Shown(object sender, EventArgs e)
        {
            
            StartDownload();
        }

        private void Download_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            this.Close();
        }
        public void SetspecificText(Label label, string str)
        {
            if (label.InvokeRequired)
            {
                BeginInvoke(new Action<string>(x => { label.Text = x.ToString(); }), str);
            }
            else
            {
                label.Text = str;
            }
        }
    }

    public class HttpFile2
    {
        public Upgrade formm;//声明一个窗体类
        public int threadIndex;//进程标识
        public string filenamea;//下载的小文件名
        public string strUrl;//请求的链接
        public FileStream fs;
        public HttpWebRequest request;
        public HttpWebResponse response;
        public Stream ns;
        public byte[] nbytes;//接收缓冲区
        public int nreadsize;//接收字节数


        public HttpFile2(Upgrade form, int thread)
        {
            formm = form;
            threadIndex = thread;
        }
        ~HttpFile2()
        {
            formm.Dispose();
        }
        public int GetThread
        {
            get
            {
                return threadIndex;
            }
        }
        public int GetFilesize
        {
            get
            {
                return formm.filesize[threadIndex];
            }
        }
        public void ReceiveFile()//线程开始接收文件
        {
            filenamea = formm.filenameList[threadIndex];
            strUrl = formm.DownloadLink;
            ns = null;
            nbytes = new byte[1024];
            nreadsize = 0;
            //formm.recevMsg.Items.Add("线程" + threadIndex.ToString() + "开始接收：" + "文件大小" + Math.Ceiling(formm.filesize[threadIndex] / 1024.0f) + "KB");
            formm.ProgressBar1.Maximum = Convert.ToInt32(Math.Ceiling(formm.filesize[threadIndex] / 1024.0f));
            fs = new FileStream(filenamea, FileMode.Create);           
            
            try
            {                              
                request = (HttpWebRequest)WebRequest.Create(strUrl);
                request.KeepAlive = false;
                //request.ProtocolVersion = HttpVersion.Version10;
                request.Proxy = null;//WebRequest.DefaultWebProxy;//不使用代理，减少自动搜索代理的过程，提升性能
                //要接收文件的字节范围
                //request.AddRange(formm.filestartpos[threadIndex], formm.filestartpos[threadIndex] + formm.filesize[threadIndex]);
                request.Timeout = 5 * 60 * 1000;
                System.Net.ServicePointManager.DefaultConnectionLimit = 200;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
                response = request.GetResponse() as HttpWebResponse;
                ns = response.GetResponseStream();
                nreadsize = ns.Read(nbytes, 0, nbytes.Length);
                int preocess = 0;
                while (nreadsize > 0)
                {
                    fs.Write(nbytes, 0, nreadsize);
                    //formm.recevMsg.Items.Add("线程" + threadIndex.ToString() + "已下载字节：" + Math.Ceiling(nreadsize / 1024.0f) + "KB");                   
                    nreadsize = ns.Read(nbytes, 0, nbytes.Length);                  
                    preocess += (int)Math.Ceiling(nreadsize / 1024.0f);
                    if(preocess<= formm.ProgressBar1.Maximum)
                    {
                        formm.ProgressBar1.Value = preocess;
                    }
                }
                fs.Close();
                ns.Close();
                response.Close();
                GC.Collect();
                CommonMethod.UpgradeReport(UpgradeReportUrl.Officialurl, formm.factorynumNow, "Success", formm.errorDBNow);
                MessageBox.Show(LResource.UpgradeDownloadSuccess);
                System.Diagnostics.Process.Start(formm.filenameList[0]);
                Thread.Sleep(500);
                Environment.Exit(0);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, LResource.Error) ;
                Log.WriteErrorLog("\r\nDownload error:" + ex.Message);
                CommonMethod.ReportErrormsg("Fail to download upgrade package", ex.Message+"\r\ndownload link:"+ formm.DownloadLink, formm.errorDBNow);
                fs.Close();
                response.Close();
                formm.Close();
                GC.Collect();
                return;
            }
            
            formm.Close();            
        }


        private static string JSON_SeleteNode(JToken json, string ReName)
        {
            try
            {
                string result = "";
                //这里6.0版块可以用正则匹配
                var node = json.SelectToken("$.." + ReName);
                if (node != null)
                {
                    //判断节点类型
                    if (node.Type == JTokenType.String || node.Type == JTokenType.Integer || node.Type == JTokenType.Float)
                    {
                        //返回string值
                        result = node.Value<object>().ToString();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

    }


}
