using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32;

namespace KellermanSoftware.ConfigHelperDemo
{
    public static class Util
    {
        public static bool ValidRequiredField(ErrorProvider errorProvider, Label label, TextBox textBox)
        {
            if (String.IsNullOrEmpty(textBox.Text))
            {
                errorProvider.SetError(textBox, string.Format("{0} is a required field", label.Text));
                return false;
            }

            return true;
        }

        public static bool ErrorProviderHasErrors(ErrorProvider errorProvider)
        {
            return errorProvider.ContainerControl.Controls.Cast<Control>().All(c => errorProvider.GetError(c) == "");
        }

        /// <summary>
        /// Execute an external program.
        /// </summary>
        /// <param name="sExecutablePath">Path and filename of the executable.</param>
        /// <param name="sArguments">Arguments to pass to the executable.</param>
        /// <param name="myWindowStyle">Window style for the process (hidden, minimized, maximized, etc).</param>
        /// <param name="bWaitUntilFinished">Wait for the process to finish.</param>
        /// <returns>Exit Code</returns>
        public static int Shell(string sExecutablePath, string sArguments, ProcessWindowStyle myWindowStyle, bool bWaitUntilFinished)
        {
            string sFileName = "";

            try
            {
                bool bDebug = false;
                Process p = new Process();
                string sAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                    Path.GetFileName(sExecutablePath));

                //Look for the file in the executing assembly directory
                if (File.Exists(sAssemblyPath))
                {
                    sFileName = sAssemblyPath;
                    p.StartInfo.FileName = sAssemblyPath;
                }
                else // if there is no path to the file, an error will be thrown
                {
                    sFileName = sExecutablePath;
                    p.StartInfo.FileName = sExecutablePath;
                }

                p.StartInfo.Arguments = sArguments;

                if (bDebug)
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                }
                else
                {
                    p.StartInfo.UseShellExecute = true;
                    p.StartInfo.WindowStyle = myWindowStyle;
                }

                //Start the Process
                p.Start();

                if (bWaitUntilFinished)
                {
                    p.WaitForExit();

                    while (!p.HasExited)
                        System.Threading.Thread.Sleep(500);
                }

                if (bWaitUntilFinished == true)
                    return p.ExitCode;
                else
                    return 0;
            }
            catch
            {
                string sMsg = "Shell Fail:  " + sFileName + "\n";
                sMsg += "Arguments:  " + sArguments;
                throw new Exception(sMsg);
            }
        }

        /// <summary>
        /// Return the name of the company using an information from registry or 
        /// the given default value.
        /// </summary>
        /// <param name="defaultName"></param>
        /// <returns></returns>
        public static string GetCompanyName(string defaultName)
        {
            string companyName = null;

            try
            {
                string keyPath = @"Software\Microsoft\Windows\CurrentVersion";
                using (var key = Registry.LocalMachine.OpenSubKey(keyPath))
                {
                    if (key != null)
                    {
                        object value = key.GetValue("RegisteredOrganization");
                        companyName = value == null ? null : value.ToString();
                    }
                }

                if (companyName == null)
                {
                    keyPath = @"Software\Microsoft\Windows NT\CurrentVersion";
                    using (var key = Registry.LocalMachine.OpenSubKey(keyPath))
                    {
                        if (key != null)
                        {
                            object value = key.GetValue("RegisteredOrganization");
                            companyName = value == null ? null : value.ToString();
                        }
                    }
                }
            }
            catch
            {
                return defaultName;
            }

            return string.IsNullOrEmpty(companyName) ? defaultName : companyName;
        }
    }
}
