using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.IO;

namespace Mes.AutoUpdate
{
    public partial class AutoUpdate : Form
    {
        private DataSet ServerSet;
        private DataSet LocalSet;

        public AutoUpdate()
        {
            InitializeComponent();
        }

        private void AutoUpdater_Load(object sender, EventArgs e)
        {
            Text += string.Format("  [{0}]", Application.ProductVersion.ToString());
            base.Visible = false;
            string hTTP_Address;
            try
            {
                hTTP_Address = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["downloadUrl"].Value.ToString();
                UriBuilder httpUb = new UriBuilder(hTTP_Address);
                if (httpUb.Scheme.ToUpper() != "HTTP") httpUb.Scheme = "HTTP";
                hTTP_Address = httpUb.ToString();
            }
            catch
            {
                hTTP_Address = "http://172.16.0.108:9998/";
            }
            string fTP_Address;
            try
            {
                fTP_Address = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["downloadFtpUrl"].Value.ToString();
                UriBuilder ftpUb = new UriBuilder(fTP_Address);
                if (ftpUb.Scheme.ToUpper() != "FTP") ftpUb.Scheme = "Ftp";
                fTP_Address = ftpUb.ToString();
            }
            catch
            {
                fTP_Address = "ftp://172.16.0.108:21/";
            }
            string value;
            try
            {
                value = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["downloadUrlfile"].Value.ToString();
            }
            catch
            {
                value = "filelist.xml";
            }
            ArrayList arrayList = new ArrayList();
            ArrayList arrayList2 = new ArrayList();
            WebRequest.DefaultWebProxy = null;
            try
            {
                try
                {
                    ArrayList Finished = new ArrayList();
                    ArrayList arrayList3 = new ArrayList();
                    arrayList3.Add(value);
                    DownManager.DownLoad(arrayList3, hTTP_Address, fTP_Address, null, null, 1, out Finished);
                }
                catch (Exception ex)
                {
                    throw new Exception("下载服务器更新列表失败！\n" + ex.Message);
                }
                ServerSet = new DataSet();
                ServerSet.ReadXml(Application.StartupPath + "\\filelist.xml");
                DataTable dataTable = ServerSet.Tables["file"];
                Hashtable hashtable = new Hashtable();
                LocalSet = new DataSet();
                foreach (DataRow row in dataTable.Rows)
                {
                    string key = row["filename"].ToString().ToUpper();
                    int result = 0;
                    int.TryParse(row["var"].ToString(), out result);
                    if (hashtable.ContainsKey(key))
                    {
                        if ((int)hashtable[key] < result)
                        {
                            hashtable[key] = result;
                        }
                    }
                    else
                    {
                        hashtable.Add(key, result);
                    }
                }
                if (File.Exists(Application.StartupPath + "\\myfilelist.xml"))
                {
                    LocalSet.ReadXml(Application.StartupPath + "\\myfilelist.xml");
                    DataTable dataTable2 = CreateFileDataTable();
                    if (LocalSet.Tables.Contains("file"))
                    {
                        foreach (DataRow row2 in LocalSet.Tables["file"].Rows)
                        {
                            row2["filename"] = row2["filename"].ToString().ToUpper();
                        }
                        LocalSet.Tables["file"].AcceptChanges();
                        dataTable2 = LocalSet.Tables["file"];
                    }
                    else
                    {
                        LocalSet.Tables.Add(dataTable2);
                    }
                    foreach (string key2 in hashtable.Keys)
                    {
                        int result2 = 0;
                        int.TryParse(hashtable[key2].ToString(), out result2);
                        string text2 = Path.Combine(Application.StartupPath, key2).ToUpper();
                        string text3 = Path.GetFullPath(text2).ToUpper();
                        string text4 = Path.GetFileName(text2).ToUpper();
                        if (result2 > 0 && !File.Exists(text2))
                        {
                            arrayList.Add(key2);
                        }
                        else if (result2 <= 0)
                        {
                            if (File.Exists(text2))
                            {
                                File.Move(text2, text2 + "." + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                            }
                        }
                        else
                        {
                            DataRow[] array = new DataRow[0];
                            if (dataTable2.Columns.Contains("filename"))
                            {
                                array = dataTable2.Select("filename='" + key2 + "'");
                            }
                            if (array != null && array.Length > 0)
                            {
                                int num = 0;
                                for (int i = 0; i < array.Length; i++)
                                {
                                    int result = 0;
                                    int.TryParse(array[0]["var"].ToString(), out result);
                                    if (i == 0 || result > num)
                                    {
                                        num = result;
                                    }
                                }
                                if ((int)hashtable[key2] != num && !arrayList.Contains(key2))
                                {
                                    arrayList.Add(key2);
                                }
                            }
                            else if (!arrayList.Contains(key2))
                            {
                                arrayList.Add(key2);
                            }
                        }
                    }
                }
                else
                {
                    foreach (string key3 in hashtable.Keys)
                    {
                        if (!arrayList.Contains(key3))
                        {
                            arrayList.Add(key3);
                        }
                    }
                }
                foreach (DataTable table in ServerSet.Tables)
                {
                    if (!(table.TableName.ToUpper() == "FILE") && !LocalSet.Tables.Contains(table.TableName))
                    {
                        LocalSet.Tables.Add(table.Copy());
                    }
                }
                if (arrayList.Count > 0)
                {
                    StopProcess("Core.Mes.ClientManager");
                    base.Visible = true;
                    ArrayList arrayList4 = new ArrayList();
                    string str = Convert.ToString(ServerSet.Tables["path"].Rows[0][0]).ToUpper();
                    foreach (string item in arrayList)
                    {
                        arrayList4.Add(str + item);
                    }
                    arrayList2 = Updater(arrayList4, hTTP_Address, fTP_Address);
                    DataTable dataTable4 = CreateFileDataTable();
                    Hashtable hashtable2 = new Hashtable();
                    if (LocalSet.Tables.Contains("file"))
                    {
                        foreach (DataRow row3 in LocalSet.Tables["file"].Rows)
                        {
                            string text6 = row3["filename"].ToString().ToUpper();
                            int result3 = 0;
                            int.TryParse(row3["var"].ToString(), out result3);
                            if (!hashtable2.ContainsKey(text6))
                            {
                                if (File.Exists(Path.Combine(Application.StartupPath, text6).ToUpper()))
                                {
                                    hashtable2.Add(text6, result3);
                                }
                            }
                            else if ((int)hashtable2[text6] > result3)
                            {
                                hashtable2[text6] = result3;
                            }
                        }
                    }
                    foreach (string item2 in arrayList2)
                    {
                        string text8 = item2.ToUpper();
                        int num2 = (int)hashtable[text8];
                        if (!hashtable2.ContainsKey(text8))
                        {
                            if (File.Exists(Path.Combine(Application.StartupPath, text8)))
                            {
                                hashtable2.Add(text8, num2);
                            }
                        }
                        else
                        {
                            hashtable2[text8] = num2;
                        }
                    }
                    foreach (string key4 in hashtable2.Keys)
                    {
                        DataRow dataRow2 = dataTable4.NewRow();
                        dataRow2["filename"] = key4.ToUpper();
                        dataRow2["var"] = hashtable2[key4.ToUpper()].ToString();
                        dataTable4.Rows.Add(dataRow2);
                    }
                    dataTable4.AcceptChanges();
                    if (LocalSet.Tables.Contains("file"))
                    {
                        LocalSet.Tables.Remove("file");
                    }
                    LocalSet.Tables.Add(dataTable4);
                    LocalSet.AcceptChanges();
                    File.Delete(Application.StartupPath + "\\myfilelist.xml");
                    LocalSet.WriteXml(Application.StartupPath + "\\myfilelist.xml");
                }
                Process.Start(Application.StartupPath + "\\Core.Mes.ClientManager.exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Close();
                Application.Exit();
            }
        }

        private DataTable CreateFileDataTable()
        {
            DataTable dataTable = new DataTable("file");
            dataTable.Columns.AddRange(new DataColumn[2]
		{
			new DataColumn("filename", typeof(string)),
			new DataColumn("var", typeof(string))
		});
            dataTable.AcceptChanges();
            return dataTable;
        }

        private ArrayList Updater(ArrayList files, string HTTP_Address, string FTP_Address)
        {
            ArrayList Finished = null;
            lock (files)
            {
                try
                {
                    DownManager.DownLoad(files, HTTP_Address, FTP_Address, Main_Progress, Show_Progress, 1, out Finished);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "更新出错!", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            return Finished;
        }

        private void Main_Progress(int _A, int _B)
        {
            Application.DoEvents();
            progressBar1.Maximum = _B;
            progressBar1.Value = _A;
        }

        private void Show_Progress(string main_progress, string sub_progress)
        {
            Application.DoEvents();
            lblfile.Text = string.Format("{0} [{1}]", main_progress, sub_progress);
        }

        private void StopProcess(string processName)
        {
            try
            {
                Process[] processesByName = Process.GetProcessesByName(processName);
                Process[] array = processesByName;
                foreach (Process process in array)
                {
                    try
                    {
                        if (processName.Length >= 4 && processName.Substring(processName.Length - 4, 4).ToUpper() != ".EXE")
                        {
                            processName += ".EXE";
                        }
                        string path = Path.Combine(Application.StartupPath, processName);
                        if (Path.GetFullPath(process.MainModule.FileName).ToUpper() == Path.GetFullPath(path).ToUpper())
                        {
                            if (MessageBox.Show("检测到客户端正在运行，是否强制关闭?", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                process.Kill();
                            }
                            else
                            {
                                Close();
                                Application.Exit();
                            }
                        }
                    }
                    catch { }
                }
            }
            catch (InvalidOperationException ex)
            {
                Debug.Print(ex.Message);
            }
            catch (Exception ex2)
            {
                throw ex2;
            }
        }


    }
}
