using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel.Configuration;

namespace Valg.EVA.Skanning.Configuration
{
    public class ApplicationConfigurationReader : IApplicationConfigurationReader
    {
        private readonly System.Configuration.Configuration configuration;

        public ApplicationConfigurationReader(IConfigurationFileProvider configurationFileProvider)
        {
            configuration = configurationFileProvider.GetConfiguration();
        }

        public string GetConnectionString()
        {
            var value = configuration.ConnectionStrings.ConnectionStrings["ScanningDatabase"]?.ConnectionString;

            if (string.IsNullOrEmpty(value))
            {
                throw new ConfigurationErrorsException("The connection string 'ScanningDatabase' is missing or empty.");
            }

            return value;
        }

        public string GetTransferWebServiceUrl()
        {
            var url = string.Empty;
            var section = (ClientSection)configuration.GetSection("system.serviceModel/client");
            var enumerator = section.Endpoints.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var configElement = (ChannelEndpointElement)enumerator.Current;
                if (configElement.Name == "TransferWebService")
                {
                    url = configElement.Address.Host;
                }
            }

            return url;
        }
        
        public string GetAppSetting(string appSettingName)
        {
            var setting = configuration.AppSettings.Settings[appSettingName];

            if (setting == null)
            {
                throw new ConfigurationErrorsException($"The required AppSettings key '{appSettingName}' is missing or empty.");
            }

            return setting.Value;
        }

        public string GetOptionalAppSetting(string appSettingKey)
        {
            if (configuration.AppSettings.Settings.AllKeys.Contains(appSettingKey))
            {
                return configuration.AppSettings.Settings[appSettingKey].Value;
            }

            return string.Empty;
        }

        public Dictionary<string,string> GetAppSettingsStartsWith(string appSettingName)
        {
            var appSettingsStartsWith = new Dictionary<string, string>();
            var allKeys = configuration.AppSettings.Settings.AllKeys;
            foreach (var keyName in allKeys.Where(p => p.Contains(appSettingName)))
            {
                appSettingsStartsWith.Add(keyName, configuration.AppSettings.Settings[keyName].Value);
            }
            return appSettingsStartsWith;
        }
    }
}

