using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eDosStation
{
    static class Config
    {
        public static void ToggleConfigEncryption(string exeConfigName, string pwd)
        {
            // Takes the executable file name without the
            // .config extension.
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(exeConfigName);
                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
                
                if (section.SectionInformation.IsProtected)
                {
                    // Remove encryption.
                    //section.SectionInformation.UnprotectSection();
                }
                else
                {
                    var x = section.ConnectionStrings["eDosStation.Properties.Settings.eDosConnectionString"].ConnectionString;
                    var cb = new System.Data.SqlClient.SqlConnectionStringBuilder(x);
                    
                    cb.Password = pwd;
                    section.ConnectionStrings["eDosStation.Properties.Settings.eDosConnectionString"].ConnectionString = cb.ConnectionString;
                    // Encrypt the section.
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }
                // Save the current configuration.
                config.Save();

                Console.WriteLine("Protected={0}",section.SectionInformation.IsProtected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
