using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
namespace AutoUpdateTool
{
    public partial class FormUp : System.Windows.Forms.Form
    {
        public FormUp()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string filepath = System.Windows.Forms.Application.StartupPath + @"\AIMS.xml";
            if (!File.Exists(filepath))
            {
                MessageBox.Show("AIMS.xml不存在!", "系统提示");
                return;
            }
            string connstr = GetConnStr(filepath);
            //if (!dbHelper.CanOpen)
            //{
            //    MessageBox.Show("数据库连接配置不正确,请检查:ConnectionString配置。");
            //    return;
            //}
            nowVersion.Text = GetVersion();
            upVersion.Text = nowVersion.Text;
        }
        private void btnLoad_Click(object sender, EventArgs e)
        {
            string localXmlFile = Application.StartupPath + "\\UpdateList.xml";
            if (!File.Exists(localXmlFile))
            {
                MessageBox.Show("UpdateList.xml不存在!", "系统提示");
                return;
            }
            SetVersion(upVersion.Text);
            UpdateListXML(upVersion.Text);
            MessageBox.Show("生成成功 可以替换ftp了。", "系统提示");
            this.Close();
        }
        private string GetConnStr(string filepath)
        {
            XmlOperator xmlOperator = new XmlOperator(filepath);
            return xmlOperator.GetNode("ConnectionString")[0].ToString();
        }
        /// 
        /// 修改程序版本号
        /// 
        /// 
        public void SetVersion(string Version)
        {
            string strSql = "update Version set VerName='" + Version + "'";
            DBHelper.ExecNonQuery(strSql);
        }
        /// 
        /// 获取程序版本号
        ///  
        public string GetVersion()
        {
            string strSql = "select * from Version";
            return DBHelper.ExecuteScalar(strSql).ToString();
        }
        public List nowListFileDirectory;
        public void UpdateListXML(string vs)
        {
            try
            {
                string localXmlFile = Application.StartupPath + "\\UpdateList.xml";
                if (!File.Exists(localXmlFile)) return;
                //读xml版本号
                XElement xe = XElement.Load(localXmlFile);
                xe.Element("Version").Value = vs.ToString();
                nowListFileDirectory = new List();
                downNow(Application.StartupPath);
                IEnumerable element = from ex in xe.Elements("Files")
                                                select ex;
                ///删除指定的元素,并保存
                if (element.Count() > 0)
                {
                    element.Remove();
                }
                XElement record = new XElement("Files");
                foreach (var item in nowListFileDirectory)
                {
                    if (item.filename.Contains("AutoUpdate")) continue;
                    XElement file = new XElement(
                    new XElement("File",
                    new XAttribute("Name", item.filename),
                    new XAttribute("MD5Hash", item.MD5Hash == null ? "" : item.MD5Hash)));
                    record.Add(file);
                }
                xe.Add(record);
                xe.Save(localXmlFile);
            }
            catch (Exception)
            {
                return;
            }
        }
        /// 
        /// 递归实现获取ftp目录下所有文件及文件夹以及文件夹内的子文件
        /// 
        /// FTP路径
        /// 保存的本地路径
        /// 用户名
        /// 密码
        public void downNow(string ftpads)
        {
            try
            {
                DirectoryInfo theFolder = new DirectoryInfo(ftpads);
                printAllFile(theFolder);
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取目录失败+downftp" + ex.ToString());
                Environment.Exit(0);
            }
        }
        public void printAllFile(DirectoryInfo di)
        {
            FileInfo[] fiArray = di.GetFiles();
            DirectoryInfo[] diArray = di.GetDirectories();
            foreach (FileInfo NextFile in fiArray)
            { 
                var fd = new ftpFileDirectory();
                fd.ftpPath = NextFile.DirectoryName + "\\" + NextFile.Name.ToString();
                fd.filename = NextFile.Name.ToString();
                fd.filelength = NextFile.Length;
                fd.MD5Hash = GetMD5HashFromFile(fd.ftpPath);
                nowListFileDirectory.Add(fd);
            }
            foreach (DirectoryInfo inst in diArray)
            {
                printAllFile(inst);
            }
        }
        ///   
        /// 获取文件的MD5码  
        ///   
        /// 传入的文件名(含路径及后缀名)  
        ///   
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                return "";
                //throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
    }
    /// 
    /// 记录要下载的文件路径及下载到本地的路径
    /// 
    public struct ftpFileDirectory
    {
        /// 
        /// 要下载的文件路径
        /// 
        public string ftpPath;
        /// 
        /// 下载到本地的路径
        /// 
        public string localPath;
        /// 
        /// 文件名
        /// 
        public string filename;
        /// 
        /// 文件大小
        /// 
        public long filelength;
        /// 
        /// MD5码
        /// 
        public string MD5Hash;
    }
}