using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Install.Core.Common
{
    public static class InstallInfoHelper
    {
        /// <summary>
        /// 从注册表获取已经安装程序信息
        /// </summary>
        /// <returns></returns>
        public static List<InstallInfo> GetInstallInfos()
        {
            List<InstallInfo> installInfos = new List<InstallInfo>();

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\FLYAutomation"); //该项必须已存在
            if (key == null)
            {
                //没有安装任何软件
                return installInfos;
            }
            
            string[] subKeyNames = key.GetSubKeyNames();
            for (int i = 0; i < subKeyNames.Count(); i++)
            {
                string subKeyName = subKeyNames[i];
                var subKey = key.OpenSubKey(subKeyName);
                string exePath = subKey.GetValue("ExePath") as string;
                string installPath = subKey.GetValue("InstallPath") as string;
                string name = subKey.GetValue("Name") as string;

                //版本信息从实际的执行文件获取
                //string version = subKey.GetValue("Version") as string;
                if ((exePath == null) || (installPath == null) || (name == null))
                    continue;

                string path = System.IO.Path.Combine(installPath, exePath);
                if (!File.Exists(path))
                {
                    //执行文件不存在,这个没有用的安装信息   
                    continue;
                }

                FileVersionInfo fileVerInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(path);
                //版本号显示为“主版本号.次版本号.内部版本号.专用部件号”。
                string version = String.Format("{0}.{1}.{2}.{3}", fileVerInfo.FileMajorPart, fileVerInfo.FileMinorPart, fileVerInfo.FileBuildPart, fileVerInfo.FilePrivatePart);
                    
                InstallInfo installInfo = new InstallInfo()
                {
                    InstallPath = installPath,
                    Exe = System.IO.Path.GetFileName(exePath),
                    Name = name,
                    Version = version
                };
                installInfo.IsAutoRun = CheckAutoRun(installInfo);
                installInfos.Add(installInfo);
                
            }
            return installInfos;
        }

        /// <summary>
        /// 从路径获取已经安装程序信息
        /// </summary>
        /// <returns></returns>
        public static List<InstallInfo> GetInstallInfosFromPath(InstallPackCollection installPackCollection)
        {
            List<InstallInfo> installInfos = new List<InstallInfo>();

            string installBasePath = installPackCollection.DefaultInstallPath;

            if (!Directory.Exists(installBasePath))
                return installInfos;




            foreach (var installPack in installPackCollection.Items) { 

                string installPath = $@"{installBasePath}\{installPack.ProcessName}";
                string filePath = $@"{installPath}\{installPack.Exe}";
                if (!File.Exists(filePath))
                    continue;//这个软件不存在

                FileVersionInfo fileVerInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(filePath);
                //版本号显示为“主版本号.次版本号.内部版本号.专用部件号”。
                string version = String.Format("{0}.{1}.{2}.{3}", fileVerInfo.FileMajorPart, fileVerInfo.FileMinorPart, fileVerInfo.FileBuildPart, fileVerInfo.FilePrivatePart);

                InstallInfo installInfo = new InstallInfo()
                {
                    InstallPath = installPath,
                    Exe = System.IO.Path.GetFileName(installPack.Exe),
                    Name = installPack.Name,
                    Version = version
                };
                installInfo.IsAutoRun = CheckAutoRun(installInfo);

                //补充安装信息
                SetInstallInfo(installInfo);


                installInfos.Add(installInfo);

            }

            return installInfos;
        }



        public static bool SetInstallInfo(InstallInfo item)
        {
            RegistryKey key3 = Registry.CurrentUser.OpenSubKey($@"Software\FLYAutomation\{item.KeyName}", true);
            if (key3 == null)
                key3 = Registry.CurrentUser.CreateSubKey($@"Software\FLYAutomation\{item.KeyName}", RegistryKeyPermissionCheck.ReadWriteSubTree);

            key3.SetValue("Name", item.Name);
            key3.SetValue("ExePath", item.ExePath);
            key3.SetValue("InstallPath", item.InstallPath);
            key3.SetValue("Version", item.Version);
            key3.Close();
            return true;
        }
        public static void RemoveInstallInfo(InstallInfo item)
        {
            Registry.CurrentUser.DeleteSubKey(@"Software\FLYAutomation\" + item.KeyName, false);
        }
        public static void SetAutoRun(InstallInfo item)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            key.SetValue(item.KeyName, item.ShortcutPath);
            key.Close();
        }
        public static bool CheckAutoRun(InstallInfo item)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");

            object o = key.GetValue(item.KeyName);
            key.Close();
            if (string.IsNullOrEmpty(o as string))
                return false;
            else
                return true;
        }
        public static void RemoveAutoRun(InstallInfo item)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            key.DeleteValue(item.KeyName, false);
            key.Close();
        }
    }

}
