using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Yaulw.Process;
using Yaulw.Tools;
using System.IO;
using Yaulw.File;
using Yaulw.Xml;
using System.Reflection;

namespace Installables.All
{
    /// <summary>
    /// Common Functions and Helpers Useful for all Installing activities.
    /// </summary>
    public static class Common
    {
        #region Public Definitions

        public const string INSTALLED_COMPONENT_CONFIG_XML_FILENAME = "InstalledComponentConfig.xml";
        public const string EMBEDDED_COMPONENT_CONFIG_XML_FILENAME = "EmbeddedComponentConfig.xml";

        /// <summary>
        /// Allow Setting of Log by external Assembly
        /// </summary>
        public static Logging Log 
        {
            get
            {
                return s_Log;
            }
            set
            {
                if (value != null)
                    s_Log = value;
            }
        }

        #endregion

        #region Private Statics

        private static ISReadWrite s_isrw = null;
        private static XSerializer s_serializer = null;
        private static ComponentConfig s_EmbeddedComponentConfig = null;
        private static ComponentConfig s_InstalledComponentConfig = null;
        private static Logging s_Log = null;

        #endregion

        #region Construction

        /// <summary>
        /// Responsible for reading in embedded and installed configuration
        /// </summary>
        static Common()
        {
            s_isrw = new ISReadWrite(INSTALLED_COMPONENT_CONFIG_XML_FILENAME);
            s_serializer = new XSerializer();

            //# Read in from Resource (Embedded Components)
            s_EmbeddedComponentConfig = s_serializer.ReadFromResource<ComponentConfig>(Assembly.GetExecutingAssembly().GetManifestResourceStream("Installables.All." + EMBEDDED_COMPONENT_CONFIG_XML_FILENAME));
            if (s_EmbeddedComponentConfig == null)
                throw new Exception("Could not read in EmbeddedComponentConfig"); // should never happen

            //# Read in from IS (Currently Installed Components)
            s_InstalledComponentConfig = s_isrw.ReadFromIS<ComponentConfig>();
            if (s_InstalledComponentConfig == null)
                s_InstalledComponentConfig = new ComponentConfig();
        }

        #endregion

        #region Public Statics

        /// <summary>
        /// Retrieve the EmbeddedComponentConfig
        /// </summary>
        /// <returns>the EmbeddedComponentConfig</returns>
        public static ComponentConfig EmbeddedConfig
        {
            get
            {
                return s_EmbeddedComponentConfig;
            }
        }

        /// <summary>
        /// Retrieve the InstalledComponentConfig
        /// </summary>
        /// <returns>the InstalledComponentConfig or null, if not existent</returns>
        public static ComponentConfig InstalledConfig
        {
            get
            {
                return s_InstalledComponentConfig;
            }
        }

        /// <summary>
        /// Allows Caller to write out any changes to InstalledConfig back to the File
        /// </summary>
        public static void WriteOutChangesToInstalledConfig()
        {
            s_isrw.WriteToIS<ComponentConfig>(s_InstalledComponentConfig);
        }

        /// <summary>
        /// Checks to see if any Components are installed. If this returns false, then this is a Fresh Install
        /// </summary>
        /// <returns>true, if any components are installed, false otherwise</returns>
        public static bool AreAnyComponentsInstalled()
        {
            bool bIsInstalled = (InstalledConfig != null) && (InstalledConfig.BinaryComponents.Components.Length > 0 || InstalledConfig.SetupComponents.Components.Length > 0);
            return bIsInstalled;
        }

        /// <summary>
        /// Retrieves the Index for the Component that matches the specified Unique Label
        /// </summary>
        /// <param name="UniqueLabel">label to search components for</param>
        /// <param name="components">a component array</param>
        /// <returns>a value >=0 or -1, if not found</returns>
        public static int GetIndexForComponentUniqueLabel(string UniqueLabel, ComponentConfig.Component[] components)
        {
            if (String.IsNullOrEmpty(UniqueLabel) || components == null || components.Length <= 0)
                return -1;

            for (int i = 0; i < components.Length; ++i)
            {
                if (String.Compare(components[i].UniqueLabel, UniqueLabel, true) == 0)
                    return i;
            }
            return -1;
        }
        
        /// <summary>
        /// Spawn a Setup Process (Setup.exe for example)
        /// </summary>
        public static void PSetupSpwan(string SetupFileNameNPath, string param_s)
        {
            PStarter.StartProcess(PStartInfo.CreateProcess(SetupFileNameNPath, param_s, "", true, System.Diagnostics.ProcessWindowStyle.Hidden, false), true, false);
        }

        /// <summary>
        /// Spawn a MSI Setup Process (*.msi)
        /// </summary>
        public static void PSetupMSIEXEC(string param_s)
        {
            string msiexec = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\msiexec.exe";
            PStarter.StartProcess(PStartInfo.CreateProcess(msiexec, param_s, "", true, System.Diagnostics.ProcessWindowStyle.Hidden, false), true, false);
        }

        /// <summary>
        /// Run a command on the commandline * Hidden *
        /// </summary>
        /// <param name="cmdline">cmd to run</param>
        public static string RunCmdLine(string cmdline)
        {
            string result = PStarter.RunDosCommand(cmdline);
            return result;
        }

        /// <summary>
        /// Use this to get the complete path to a .net framework utility like gacutil.exe or 
        /// installutil.exe.. any .net framework utility. Will fall back to look in the %temp% folder,
        /// if not found, giving the opportunity to deploy the util directly with the components
        /// </summary>
        /// <param name="UtilFileName">the utility in .net you are looking for like gacutil.exe</param>
        /// <returns>the full filenameNpath or "", if no existing file found</returns>
        public static string GetNetFrameworkUtilFileNameNPathFile(string UtilFileName)
        {
            string windir = System.Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine);
            string NetFramework1_0 = windir + "\\Microsoft.Net\\Framework\\v1.0.3705";
            string NetFramework1_1 = windir + "\\Microsoft.Net\\Framework\\v1.1.4322";
            string NetFramework2_0 = windir + "\\Microsoft.Net\\Framework\\v2.0.50727";
            string NetFramework3_0 = windir + "\\Microsoft.Net\\Framework\\v3.0";
            string NetFramework3_5 = windir + "\\Microsoft.Net\\Framework\\v3.5";
            string NetFramework4_0 = windir + "\\Microsoft.Net\\Framework\\v4.0.30319";
            string TempPath = PathNaming.PathEndsWithNoSlash(Path.GetTempPath()); // We use this as a Fallback, in case file doesn't exist in the framework
            string[] Frameworks = new string[] { NetFramework2_0, NetFramework4_0, NetFramework1_0, NetFramework1_1, NetFramework3_0, NetFramework3_5, TempPath };

            string NetUtilFileNameNPath = "";
            foreach (string framework in Frameworks)
            {
                if (File.Exists(framework + "\\" + UtilFileName))
                {
                    NetUtilFileNameNPath = framework + "\\" + UtilFileName;
                    return NetUtilFileNameNPath;
                }
            };
            return NetUtilFileNameNPath;
        }

        /// <summary>
        /// Quick Helper to get the Program Files Path for the specific system
        /// </summary>
        /// <returns>Program Files path with a '/' at the end</returns>
        public static string GetProgramFilesPathOnSystemWithEndSlash()
        {
            string ProgramFiles = System.Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            if (String.IsNullOrEmpty(ProgramFiles))
                ProgramFiles = System.Environment.GetEnvironmentVariable("ProgramFiles");
            return PathNaming.PathEndsWithSlash(ProgramFiles);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string SetOwnership()
        {
            // in order to do any of this, sadly, we must first install the windows resource kit
            //subinacl /subdirectories *.* /setowner=domainname\user
            return String.Empty;
        }

        /// <summary>
        /// To grant the specified User or group Full Control permissions to the folder and its contents
        /// </summary>
        /// <param name="FolderNPath">full path to folder/directory</param>
        /// <param name="UserOrGroup">domainname\administrator, any windows user or group</param>
        /// <returns></returns>
        public static bool GrantFullPermissionToFolderForUserOrGroup(string FolderNPath, string UserOrGroup)
        {
            if (Directory.Exists(FolderNPath))
            {
                string command = String.Format("cacls \"{0}\" /t /e /g {1}:f", FolderNPath, UserOrGroup);
                if (command.Contains("Invalid arguments."))
                    return false;
                else
                    return true;
            }
            return false;
        }

        /// <summary>
        /// Stop a service
        /// </summary>
        /// <param name="ServiceName">name of service to stop</param>
        /// <returns>true if successful, false otherwise</returns>
        public static bool StopService(string ServiceName)
        {
            bool bSuccess = true;
            if (ServiceW.DoesServiceExist(ServiceName))
                bSuccess = ServiceW.StopService(ServiceName, true, 120);
            return bSuccess;
        }

        /// <summary>
        /// start a service
        /// </summary>
        /// <param name="ServiceName">name of a service to start</param>
        /// <returns>true if successful, false otherwise</returns>
        public static bool StartService(string ServiceName)
        {
            bool bSuccess = true;
            if (ServiceW.DoesServiceExist(ServiceName))
                bSuccess = ServiceW.StartService(ServiceName, 120);
            return bSuccess;
        }

        /// <summary>
        /// Does Service Exist
        /// </summary>
        /// <param name="ServiceName">Name of service to check</param>
        /// <returns>true if successful, false otherwise</returns>
        public static bool ServiceExists(string ServiceName)
        {
            return ServiceW.DoesServiceExist(ServiceName);
        }

        #endregion
    }
}
