using System.Configuration;
using System.ServiceModel.Configuration;

namespace Valg.EVA.Skanning.BackgroundServices.CleanupAbandonedTransfers
{
    public class SendTimeoutFromServiceBinding : ISendTimeoutFromServiceBindingUtility
    {
        private int cachedTimeoutValue = -1;

        public int Get()
        {
            if (cachedTimeoutValue == -1)
            {
                var section = (ClientSection) ConfigurationManager.GetSection("system.serviceModel/client");

                var enumerator = section.Endpoints.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var configElement = (ChannelEndpointElement)enumerator.Current;
                    if (configElement.Name == "TransferWebService")
                    {
                        var currentBindingConfig = configElement.BindingConfiguration;
                        var bindingsSection = (BindingsSection) ConfigurationManager.GetSection("system.serviceModel/bindings");
                        var bindingsEnumerator = bindingsSection.BasicHttpBinding.Bindings.GetEnumerator();
                        while (bindingsEnumerator.MoveNext())
                        {
                            var possibleTargetConfig = (BasicHttpBindingElement) bindingsEnumerator.Current;
                            if (possibleTargetConfig.Name == currentBindingConfig)
                            {
                                cachedTimeoutValue = (int) possibleTargetConfig.SendTimeout.TotalMinutes;
                            }
                        }
                    }
                }
            }

            return cachedTimeoutValue;
        }
    }
}
