using System.IO;
using Microsoft.Win32;
using LJLib.Cmd;
using System.ServiceProcess;

namespace LJLib.InstallHelper
{
    public static class LJInstallHelper
    {
        public static string Install(string ServerName, string DisplayName, string Description, string ImagePath)
        {
            LJInstallGlobal.ServerName = ServerName;
            LJInstallGlobal.DisplayName = DisplayName;
            LJInstallGlobal.Description = Description;
            LJInstallGlobal.ImagePath = ImagePath;

            string cmd = "\"" + InstallUtilPath + "\" \"" + LJInstallGlobal.CurrentPath + "\\" + LJInstallGlobal.FileName + "\"";
            return CMDHelper.RunWithReturn(cmd);
        }

        public static string Uninstall(string ServerName)
        {
            LJInstallGlobal.ServerName = ServerName;

            string cmd = "\"" + InstallUtilPath + "\" /u \"" + LJInstallGlobal.CurrentPath + "\\" + LJInstallGlobal.FileName + "\"";
            return CMDHelper.RunWithReturn(cmd);
        }

        public static bool Exitst(string ServerName)
        {
            try
            {
                ServiceController sc = new ServiceController(ServerName);
                var status = sc.Status;
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        private static string frameworkpath
        {
            get
            {
                var netkey = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey(".NETFramework");
                return netkey.GetValue("InstallRoot").ToString();
            }
        }

        private static string InstallUtilPath
        {
            get
            {
                string fwp = frameworkpath;
                if (!fwp.EndsWith("\\"))
                {
                    fwp += "\\";
                }
                if (Directory.Exists(fwp + "v4.0.30319"))
                {
                    return fwp + "v4.0.30319\\InstallUtil.exe";
                }
                if (Directory.Exists(fwp + "v2.0.50727"))
                {
                    return fwp + "v2.0.50727\\InstallUtil.exe";
                }
                if (Directory.Exists(fwp + "v1.1.4322"))
                {
                    return fwp + "v1.1.4322\\InstallUtil.exe";
                }
                return string.Empty;
            }
        }
    }
}
