using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections;
using IWshRuntimeLibrary;
using System.Windows.Forms;
using System.Diagnostics;
using Core.Mes.Common;
using System.Net;
using System.Configuration;
using System.Data;

namespace Core.Mes.ClientManager
{
    class UpdaterManager
    {
        [DllImport("shfolder.dll", CharSet = CharSet.Auto)]
        private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
        private const int MAX_PATH = 260;
        private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;

        public static string GetAllUsersDesktopFolderPath()
        {
            StringBuilder sbPath = new StringBuilder(MAX_PATH);
            SHGetFolderPath(IntPtr.Zero, CSIDL_COMMON_DESKTOPDIRECTORY, IntPtr.Zero, 0, sbPath);
            return sbPath.ToString();
        }
        public static string GetCurrentDesktopFolderPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        }

        public static ArrayList GetAll(string ExetensionName, string dir_path, bool deep_search, int search_depth)
        {
            if (!Directory.Exists(dir_path)) return null;

            DirectoryInfo dir = new DirectoryInfo(dir_path);

            ArrayList FileList = new ArrayList();

            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                if (fi.Extension.ToUpper() == ExetensionName.ToUpper())
                    FileList.Add(Path.Combine(dir.ToString() + "/", fi.Name));
            }

            if (deep_search && (search_depth > 0 || search_depth == -1))
            {
                DirectoryInfo[] allDir = dir.GetDirectories();
                foreach (DirectoryInfo d in allDir)
                {
                    ArrayList cfl = GetAll(ExetensionName, d.ToString(), deep_search, (search_depth == -1) ? -1 : (search_depth - 1));
                    if (cfl != null)
                    {
                        FileList.AddRange(cfl);
                    }
                }
            }

            return FileList;
        }

        private static string GetTargetFileName(string Shortcurt_FilePath)
        {
            if (System.IO.File.Exists(Shortcurt_FilePath))
            {
                WshShell shell = new WshShell();
                IWshShortcut wst = (IWshShortcut)shell.CreateShortcut(Shortcurt_FilePath);
                //快捷方式文件指向的路径.Text = wst.TargetPath;
                //快捷方式文件指向的目标目录.Text = wst.WorkingDirectory;
                return wst.TargetPath;
            }
            else
            {
                return "";
            }
        }

        private static string GetUpdaterName(bool CheckExists)
        {
            string filename = Path.Combine(Application.StartupPath + @"\", "Mes.AutoUpdate.exe");

            if (CheckExists && !System.IO.File.Exists(filename))
            {
                return "";
            }
            return filename;
        }

        public static void Update_UPM()
        {
            string ServerFileVersion = "";
            string CurrentFileVersion = "0.0.0.0";
            string VerFile = Application.StartupPath + @"\" + "Mes.AutoUpdate.ver";

            bool NeedUpdate = false;
            string UpdateFileName = GetUpdaterName(true);
            if (string.IsNullOrEmpty(UpdateFileName))
            {
                NeedUpdate = true;
                UpdateFileName = GetUpdaterName(false);
            }
            else
            {
                try
                {
                    FileVersionInfo fileVerInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(UpdateFileName);
                    CurrentFileVersion = String.Format("{0}.{1}.{2}.{3}",
                       fileVerInfo.FileMajorPart, fileVerInfo.FileMinorPart, fileVerInfo.FileBuildPart, fileVerInfo.FilePrivatePart);
                }
                catch { }

                if (!System.IO.File.Exists(Application.StartupPath + @"\" + "Mes.AutoUpdate.ver"))
                {
                    ServerFileVersion = "999.999.999.999";
                }
                else
                {
                    try
                    {
                        INIFile inifile = new INIFile(VerFile);
                        ServerFileVersion = inifile.ReadValue("COMMON", "VERSION").Trim();
                    }
                    catch
                    {
                        ServerFileVersion = "999.999.999.999";
                    }
                }

                if (CheckVersion(CurrentFileVersion, ServerFileVersion)) NeedUpdate = true;

            }

            if (NeedUpdate)
            {
                WebClient wc = new WebClient();
                try
                {
                    string FileName = Path.GetFileName(UpdateFileName);
                    ExeConfigurationFileMap cfgMap = new ExeConfigurationFileMap();
                    cfgMap.ExeConfigFilename = UpdateFileName + ".CONFIG";
                    Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(cfgMap, ConfigurationUserLevel.None);
                    string url = cfg.AppSettings.Settings["downloadUrl"].Value.ToString();

                    WebClient webClient = new WebClient();
                    string sub_path = "";
                    try
                    {
                        string str = cfg.AppSettings.Settings["downloadUrlfile"].Value.ToString();
                        webClient.DownloadFile(url + str, Application.StartupPath + "\\~filelist.xml");
                        DataSet uSet = new DataSet();
                        uSet.ReadXml(Application.StartupPath + "\\~filelist.xml");
                        sub_path = Convert.ToString(uSet.Tables["path"].Rows[0][0]);
                    }
                    catch
                    {
                        sub_path = "newfiles/";
                    }
                    finally
                    {
                        webClient.Dispose();
                        System.IO.File.Delete(Application.StartupPath + "\\~filelist.xml");
                    }
                    wc.DownloadFile(url + @"/" + sub_path + Path.GetFileName(UpdateFileName), UpdateFileName + ".up");
                    System.IO.File.Delete(UpdateFileName);
                    System.IO.File.Move(UpdateFileName + ".up", UpdateFileName);
                    wc.DownloadFile(url + @"/" + sub_path + Path.GetFileName(UpdateFileName) + ".config", UpdateFileName + ".config");


                    if (!System.IO.File.Exists(Application.StartupPath + @"\" + "Mes.AutoUpdate.ver"))
                    {
                        try
                        {
                            FileVersionInfo fileVerInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(UpdateFileName);
                            CurrentFileVersion = String.Format("{0}.{1}.{2}.{3}",
                               fileVerInfo.FileMajorPart, fileVerInfo.FileMinorPart, fileVerInfo.FileBuildPart, fileVerInfo.FilePrivatePart);

                            INIFile inifile = new INIFile(VerFile);
                            inifile.WriteValue("COMMON", "VERSION", CurrentFileVersion);
                        }
                        catch
                        {
                        }
                    }
                }
                catch (Exception ex) { Debug.Print(ex.Message); }
                finally
                {
                    wc.Dispose();
                }
            }
        }

        private static bool CheckVersion(string CurrentVersion, string ServerVersion)
        {
            string[] CV = CurrentVersion.Trim().Split('.');
            string[] SV = ServerVersion.Trim().Split('.');

            for (int idx = 0; idx < 4; idx++)
            {
                int cvi = 0;
                int svi = 0;

                if (idx <= CV.GetLength(0) - 1)
                {
                    int.TryParse(CV[idx], out cvi);
                }
                if (idx <= SV.GetLength(0) - 1)
                {
                    int.TryParse(SV[idx], out svi);
                }

                if (cvi < svi) return true;
            }
            return false;
        }

        //更改桌面启动 MES主客户端 的快捷方式为启动 MES.UPDATE.
        public static void Update_Shortcut()
        {
            ArrayList lnks = GetAll(".LNK", GetAllUsersDesktopFolderPath(), true, 1);
            lnks.AddRange(GetAll(".LNK", GetCurrentDesktopFolderPath(), true, 1));
            string UpdateFileName = GetUpdaterName(true);
            string MESFileName = Path.Combine(Application.StartupPath + @"\", "Core.Mes.ClientManager.exe");

            if (string.IsNullOrEmpty(UpdateFileName)) return;

            bool existsUpdate = false;
            bool existsMes = false;
            string MesLnk = "";
            foreach (string lnk in lnks)
            {
                try
                {
                    string tg = GetTargetFileName(lnk);
                    if (Path.GetFullPath(tg).ToUpper() == Path.GetFullPath(MESFileName).ToUpper())
                    {
                        existsMes = true;
                        MesLnk = lnk;
                    }
                    else if (Path.GetFullPath(tg).ToUpper() == Path.GetFullPath(UpdateFileName).ToUpper())
                    {
                        existsUpdate = true;
                    }
                }
                catch { }
            }

            if (!existsUpdate && existsMes)
            {
                WshShell shell = new WshShell();
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(MesLnk);
                shortcut.TargetPath = Path.GetFullPath(UpdateFileName);
                shortcut.Save();
            }
        }
    }
}
