using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using KellermanSoftware.ConfigHelper;

namespace KellermanSoftware.ConfigHelperDemo
{
    public partial class frmMain : Form
    {

        #region Registry Reader Writer Code

        private void btnLoadRegistry_Click(object sender, EventArgs e)
        {
            LoadRegistrySection();
        }

        /// <summary>
        /// Load the registry section of the form
        /// </summary>
        private void LoadRegistrySection()
        {
            RegistryReaderWriter reg = new RegistryReaderWriter();

            //This is settings for the demo 
            txtCompany.Text = reg.Read("Company") != null ? reg.Read("Company").ToString() : Util.GetCompanyName("KellermanSoftware");
            txtApplication.Text = reg.Read("Application") != null ? reg.Read("Application").ToString() : "ConfigHelperDemo";
            txtKeyRegistry.Text = reg.Read("Key") != null ? reg.Read("Key").ToString() : "MyKey";
            BuildSubKey();

            //Example Code:  This is a custom registry location
            object keyValue = reg.Read(RegistryLocation.CurrentUser, lblSubKeyValue.Text, txtKeyRegistry.Text);

            txtValueRegistry.Text = keyValue == null ? string.Empty : keyValue.ToString();
            lblStatus.Text = "Registry Section Loaded";
        }

        /// <summary>
        /// Build a sub key for the registry based on the company and application names
        /// </summary>
        private void BuildSubKey()
        {
            lblSubKeyValue.Text = string.Format("Software\\{0}\\{1}", txtCompany.Text, txtApplication.Text);
        }

        private void btnSaveRegistry_Click(object sender, EventArgs e)
        {
            SaveRegistrySection();
        }

        /// <summary>
        /// Save the registry section of the form
        /// </summary>
        private void SaveRegistrySection()
        {
            if (RegistrySectionValid())
            {
                RegistryReaderWriter reg = new RegistryReaderWriter();

                //These are simply settings for the demo in the default location and subkey. They are used on form load.
                reg.Write("Company", txtCompany.Text);
                reg.Write("Application", txtApplication.Text);
                reg.Write("Key", txtKeyRegistry.Text);

                //This is a custom registry location and sub key
                reg.Write(RegistryLocation.CurrentUser, lblSubKeyValue.Text, txtKeyRegistry.Text, txtValueRegistry.Text);
                lblStatus.Text = "Registry Section Saved";
            }
        }

        /// <summary>
        /// Returns true if all the required fields are filled in
        /// </summary>
        /// <returns></returns>
        private bool RegistrySectionValid()
        {
            epValidation.Clear();

            bool valid = Util.ValidRequiredField(epValidation, lblCompany, txtCompany);
            valid = valid && Util.ValidRequiredField(epValidation, lblApplication, txtApplication);
            valid = valid && Util.ValidRequiredField(epValidation, lblKeyRegistry, txtKeyRegistry);

            if (!valid)
                lblStatus.Text = "Correct the errors to continue";

            return valid;
        }

        private void btnRegEdit_Click(object sender, EventArgs e)
        {
            Util.Shell("RegEdit", string.Empty, ProcessWindowStyle.Normal, false);
        }

        private void txtCompany_TextChanged(object sender, EventArgs e)
        {
            BuildSubKey();
        }

        private void txtApplication_TextChanged(object sender, EventArgs e)
        {
            BuildSubKey();
        }
        #endregion

        #region Config Reader Writer Code

        

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            SaveConfigSection();
        }

        /// <summary>
        /// Save the configuration section of the form
        /// </summary>
        private void SaveConfigSection()
        {
            if (ConfigSectionValid())
            {
                RegistryReaderWriter reg = new RegistryReaderWriter();

                //These are settings for the demo saved in the registry. They are used on form load
                reg.Write("ConfigFilePathValue", lblConfigFilePathValue.Text);
                reg.Write("SettingName", txtSettingName.Text);

                //This is saving to the app.config
                ConfigReaderWriter config = new ConfigReaderWriter();
                config.FilePath = lblConfigFilePathValue.Text;

                config.WriteAppSetting(txtSettingName.Text, txtValueConfig.Text);

                lblStatus.Text = "Config Section Saved";
            }
        }

        /// <summary>
        /// Returns true if all required fields are filled in
        /// </summary>
        /// <returns></returns>
        private bool ConfigSectionValid()
        {
            epValidation.Clear();

            bool valid = Util.ValidRequiredField(epValidation, lblSettingName, txtSettingName);

            if (!valid)
                lblStatus.Text = "Correct the errors to continue";

            return valid;
        }

        private void btnLoadConfig_Click(object sender, EventArgs e)
        {
            LoadConfigSection();
        }

        /// <summary>
        /// Load the configuration section of the form
        /// </summary>
        private void LoadConfigSection()
        {
            RegistryReaderWriter reg = new RegistryReaderWriter();

            //This is settings for the demo in the registry
            object configFilePath = reg.Read("ConfigFilePathValue");

            if (configFilePath != null)
            {
                lblConfigFilePathValue.Text = configFilePath.ToString();
            }
            else
            {
                lblConfigFilePathValue.Text = Path.Combine(BuildAppDataDirectory(), "app.config");
            }

            txtSettingName.Text = reg.Read("SettingName") != null ? reg.Read("SettingName").ToString() : "MySettingName";

            //This is reading from the app.config
            ConfigReaderWriter config = new ConfigReaderWriter();
            config.FilePath = lblConfigFilePathValue.Text;

            txtValueConfig.Text = config.ReadAppSetting(txtSettingName.Text);

            lblStatus.Text = "Config Section Loaded";
        }

        /// <summary>
        /// Load the config file using notepad
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNotepadConfig_Click(object sender, EventArgs e)
        {
            Util.Shell("notepad", lblConfigFilePathValue.Text, ProcessWindowStyle.Normal, false);
        }

        /// <summary>
        /// Specify a new config file location
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfigPath_Click(object sender, EventArgs e)
        {
            saveDialog.DefaultExt = ".config";
            saveDialog.Title = "Specify a config file";
            saveDialog.InitialDirectory = BuildAppDataDirectory();

            DialogResult result = saveDialog.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                lblConfigFilePathValue.Text = saveDialog.FileName;
                RegistryReaderWriter reg = new RegistryReaderWriter();
                reg.Write("ConfigFilePathValue", lblConfigFilePathValue.Text);
            }
        }
        #endregion

        #region INI Reader Writer Code
        private void btnIniPath_Click(object sender, EventArgs e)
        {
            saveDialog.DefaultExt = ".ini";
            saveDialog.Title = "Specify an INI file";
            saveDialog.InitialDirectory = BuildAppDataDirectory();

            DialogResult result = saveDialog.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                lblIniFilePathValue.Text = saveDialog.FileName;
                RegistryReaderWriter reg = new RegistryReaderWriter();
                reg.Write("IniFilePathValue", lblIniFilePathValue.Text);
            }
        }

        private void LoadIniSection()
        {
            RegistryReaderWriter reg = new RegistryReaderWriter();

            //This is settings for the demo in the registry
            object iniFilePath = reg.Read("IniFilePathValue");

            if (iniFilePath != null)
            {
                lblIniFilePathValue.Text = iniFilePath.ToString();
            }
            else
            {
                lblIniFilePathValue.Text = Path.Combine(BuildAppDataDirectory(), "demo.ini");
            }

            txtSectionNameIni.Text = reg.Read("SectionName") != null ? reg.Read("SectionName").ToString() : "MySectionName";
            txtKeyIni.Text = reg.Read("KeyIni") != null ? reg.Read("KeyIni").ToString() : "MyIniKey";

            //This is reading from the app.config
            IniReaderWriter ini = new IniReaderWriter();
            txtValueIni.Text = ini.GetSetting(txtSectionNameIni.Text, txtKeyIni.Text, lblIniFilePathValue.Text);

            lblStatus.Text = "INI Section Loaded";
        }

        private void btnLoadIni_Click(object sender, EventArgs e)
        {
            LoadIniSection();
        }

        private void btnSaveIni_Click(object sender, EventArgs e)
        {
            SaveIniSection();
        }

        private void SaveIniSection()
        {
            if (IniSectionValid())
            {
                RegistryReaderWriter reg = new RegistryReaderWriter();

                //These are settings for the demo saved in the registry. They are used on form load
                reg.Write("IniFilePathValue", lblIniFilePathValue.Text);
                reg.Write("SectionName", txtSectionNameIni.Text);
                reg.Write("KeyIni", txtKeyIni.Text);

                //This is saving to the ini file
                IniReaderWriter ini = new IniReaderWriter();
                ini.SaveSetting(txtSectionNameIni.Text, txtKeyIni.Text, txtValueIni.Text, lblIniFilePathValue.Text);

                lblStatus.Text = "INI Section Saved";
            }
        }

        private bool IniSectionValid()
        {
            epValidation.Clear();

            bool valid = Util.ValidRequiredField(epValidation, lblSectionNameIni, txtSectionNameIni);
            valid = valid && Util.ValidRequiredField(epValidation, lblKeyIni, txtKeyIni);

            if (!valid)
                lblStatus.Text = "Correct the errors to continue";

            return valid;
        }

        private void btnNotepadIni_Click(object sender, EventArgs e)
        {
            Util.Shell("notepad", lblIniFilePathValue.Text, ProcessWindowStyle.Normal, false);
        }
        #endregion

        #region Supporting Methods

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadRegistrySection();
            LoadConfigSection();
            LoadIniSection();
            lblStatus.Text = "Ready";
        }

        private string BuildAppDataDirectory()
        {
            string directory = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KellermanSoftware"), "ConfigHelperDemo");

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            return directory;
        }
        #endregion

    }
}
