using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace HighWay.Download
{
    public partial class Download : Form
    {
        public Download()
        {
            InitializeComponent();
        }

        string url = "ftp://172.18.29.24";
        string username = "";
        string password = "";
        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void Form2_Shown(object sender, EventArgs e)
        {
            try
            {
                var request = WebRequest.Create("ftp://172.18.29.24/Version.txt");
                var response = request.GetResponse();
                using (var stream = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    var content = stream.ReadToEnd();//获取到远程的页面字符串

                    Version.Text = content;// Console.WriteLine(content);
                }
            }
            catch (Exception)
            {
                ShowMessageBox("获取版本信息失败", "提示");
            }

        }


        private void DownLoad()
        {
            string download = url + "/App";
            var list = FtplistFile(download, username, password);
            string path = System.Environment.CurrentDirectory;
            TextFileCount.Text = list.Count.ToString();
            for (int i = 0; i < list.Count; i++)
            {
                Num.Text = (i + 1).ToString();
                FileName.Text = list[i];
                Ftpdownloadfile(Path.Combine(download, list[i]), Path.Combine(path, list[i]), username, password);
                progressBar.Value = ((i + 1) / list.Count) * 100;
            }
            Ftpdownloadfile(url + "/Version.txt", Path.Combine(path, "Version.txt"), username, password);

            ShowMessageBox("下载完成，打开程序？", "提示", () =>
            {
                Process m_Process = null;
                m_Process = new Process();
                m_Process.StartInfo.FileName = "HighWayAssemble.exe";
                m_Process.Start();
                this.Close();
            }, 48, () => { this.Close(); });
        }
        private List<string> FtplistFile(string url, string username, string password) //get file name form ftp folder
        {
            FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
            listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            listRequest.Credentials = new NetworkCredential(username, password);
            List<string> lines = new List<string>();

            using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
            using (Stream listStream = listResponse.GetResponseStream())
            using (StreamReader listReader = new StreamReader(listStream))
            {
                while (!listReader.EndOfStream)
                {
                    lines.Add(listReader.ReadLine());
                }
            }
            List<string> name = new List<string>();
            foreach (var line in lines)
            {
                string[] tokens =
            line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
                string n = tokens[3];
                name.Add(n);
            }
            return name;
        }

        private void Ftpdownloadfile(string to_url, string path, string username, string password)
        {
            try
            {
                FtpWebRequest request =

                (FtpWebRequest)WebRequest.Create(to_url);

                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create))
                        {
                            byte[] buffer = new byte[1024 * 4];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                                fs.Flush();
                            } while (!(read == 0));

                            fs.Flush();
                            fs.Close();
                        }
                    }
                }

            }
            catch (Exception)
            {
                throw;
            }


        }
        /// <summary>
        /// 显示 提示 框
        /// </summary>
        /// <param name="info"></param>
        /// <param name="caption"></param>
        /// <param name="icon"></param>
        /// <returns></returns>
        public bool ShowMessageBox(string info, string caption, Action Okaction = null, int icon = 0, Action Cancelaction = null)
        {
            if (MessageBox.Show(info, caption
                , MessageBoxButtons.OKCancel, (MessageBoxIcon)icon, MessageBoxDefaultButton.Button2) == DialogResult.OK)

            {
                Okaction?.Invoke();
                return true;
            }
            else
            {
                Cancelaction?.Invoke();
                return false;
            }
        }
        private void Button2_Click(object sender, EventArgs e)
        {

            try
            {
                Process m_Process = null;
                m_Process = new Process();
                m_Process.StartInfo.FileName = "HighWayAssemble.exe";
                m_Process.Close();
            }
            catch (Exception)
            {
                ShowMessageBox("请关闭主程序", "提示");
                return;
            }


            Regex regExp = new Regex(@"ftp://\d*.\d*.\d*.\d*(:[\d]{1,4})?(/[^/\s]+)*");
            if (regExp.IsMatch(textBox_url.Text))
            {
                url = textBox_url.Text;
                DownLoad();
            }
            else
            {
                ShowMessageBox("下载地址错误", "提示", null, 16);
            }
        }
    }


}
